Part VI · Complete Annotated Examples & Showcase Applications
Appendix D.1
Flagship Applications in Long Form: Widget Gallery, Canvas Workbench & TaskFlow Web Portal
Complete multi-module source listings and Light-Mode UI captures for Veko Studio Widget Gallery, Canvas Workbench, and TaskFlow Studio
Appendix D presents all six standalone multi-module applications from demos/ in complete, unabridged long form with Light-Mode visual captures.
Showcase 1: Veko Studio Widget Gallery — 33-Widget Studio UI, Clipboard/Hi-DPI & Lossless PNG Suite (demos/widget_gallery/)
Desktop UI showcase demonstrating all 29 pure-Veko immediate-mode widgets, proportional mixed-case typography (ui/font), 1D/2D flex & grid layout (ui/layout), .secret-safe masked inputs, charts, and lossless RFC 2083 PNG export (image/png).
Highlights
- 100% Pure Veko, Zero External GUI Toolkits: Runs identically across the VKO 64-bit VM, WebAssembly 3.0 sandbox (
vvm), and native Win64/Linux/macOS executables. - 4 Focused Single-View Pages (
960x600Light Mode):- Inputs & Secret Forms:
text-inputwith focus ring & caret, hardware-zeroizedsecret-input,dropdown,chip-group, multi-linetext-areawith line numbers,checkbox,toggle-switch,radio-group,slider,progress-bar/label, and primary/secondarybuttons. - Data Tables & Trees: Hierarchical
tree-viewwith disclosure triangles & badges, 5-column zebradata-tablewith semantic status pills,select-list, and mouse-wheelbegin-scroll/end-scrollinspector. - KPI Cards & Charts: 4-column
stat-cardmetric grid, labeledbar-chart, multi-series anti-aliasedline-chartwith legend, andsparklinestrip. - Split Panes & Overlays: Nested horizontal & vertical
split-panes,menu-bar,icon-buttons, right-clickcontext-menuwith shortcuts,tooltip, centeredmodallightbox, andtoastnotification.
- Inputs & Secret Forms:
Running
veko demos/widget_gallery
veko demos/widget_gallery -- --export-dir docs/screenshots
veko demos/widget_gallery -- --live
veko build --native --gui demos/widget_gallery -o dist/widget_gallery.exe




Complete Module Listings
demos/widget_gallery/veko.vk
{
name = 'widget-gallery'
version = '1.0.0'
root = 'src'
allow-caps = [.fs .clocks .env .ui]
}demos/widget_gallery/src/model.vk
1 │ // demos/widget_gallery/src/model.vk
2 │ // State model for the Veko Studio UI Widget Gallery (Light-Mode & Dark-Mode showcase).
3 │
4 │ use [w = ui/widgets]
5 │
6 │ pub GalleryModel = struct {
7 │ active_tab i64 = 0
8 │ dark_mode bool = false
9 │ active_menu i64 = 1
10 │ endpoint str = 'https://api.veko.dev/v1/cluster'
11 │ secret_len i64 = 16
12 │ runtime_idx i64 = 0
13 │ chip_flags block = [true true true true false]
14 │ editor w/EditorState = w/new-editor 'pub fetch-node = fn [host str /port p i64 = 443] str [\n // Zero-copy TLS 1.3 health probe\n `https://{host}:{p}/health`\n]'
15 │ palette w/PaletteState = w/PaletteState {}
16 │ picker w/FilePickerState = w/FilePickerState { dir = 'demos/widget_gallery/src', ext_filter = '.vk', filename = 'main.vk' }
17 │ chk_shake bool = true
18 │ chk_strict bool = true
19 │ chk_secret bool = true
20 │ sw_watch bool = true
21 │ sw_audit bool = false
22 │ opt_profile i64 = 0
23 │ workers i64 = 12
24 │ progress_pct i64 = 84
25 │ selected_tree str = 'ui/widgets.vk'
26 │ selected_row i64 = 1
27 │ scroll_y i64 = 0
28 │ selected_log i64 = 0
29 │ split_ratio i64 = 36
30 │ vsplit_ratio i64 = 58
31 │ show_modal bool = true
32 │ show_context bool = true
33 │ status_text str = 'Ready — 32 pure-Veko widgets rendered in zero-copy RGBA32'
34 │ }
35 │
36 │ pub sample-commands = fn [] block[w/CommandItem] [
37 │ [
38 │ w/CommandItem { id = 'toggle-theme', label = 'Toggle Light / Dark Studio Theme', category = 'View', shortcut = 'Ctrl+T' }
39 │ w/CommandItem { id = 'open-file', label = 'Open Workspace Veko Source...', category = 'File', shortcut = 'Ctrl+O' }
40 │ w/CommandItem { id = 'tab-inputs', label = 'Switch to Inputs & Code Editor', category = 'Navigate', shortcut = 'Alt+1' }
41 │ w/CommandItem { id = 'tab-tables', label = 'Switch to Data Tables & Trees', category = 'Navigate', shortcut = 'Alt+2' }
42 │ w/CommandItem { id = 'tab-charts', label = 'Switch to KPI Cards & Charts', category = 'Navigate', shortcut = 'Alt+3' }
43 │ w/CommandItem { id = 'tab-overlays', label = 'Switch to Split Panes & Modals', category = 'Navigate', shortcut = 'Alt+4' }
44 │ ]
45 │ ]
46 │
47 │ pub sample-files = fn [] block[w/FileEntry] [
48 │ [
49 │ w/FileEntry { name = 'assets', is_dir = true, size = 0 }
50 │ w/FileEntry { name = 'main.vk', is_dir = false, size = 4820 }
51 │ w/FileEntry { name = 'model.vk', is_dir = false, size = 3410 }
52 │ w/FileEntry { name = 'pages.vk', is_dir = false, size = 9640 }
53 │ w/FileEntry { name = 'README.md', is_dir = false, size = 1280 }
54 │ ]
55 │ ]
56 │
57 │ pub sample-tree = fn [] block[w/TreeNode] [
58 │ [
59 │ w/TreeNode { id = 'root', label = 'veko-studio', depth = 0, expanded = true, has_children = true, badge = '1.0' }
60 │ w/TreeNode { id = 'src', label = 'src', depth = 1, expanded = true, has_children = true, badge = '' }
61 │ w/TreeNode { id = 'main.vk', label = 'main.vk', depth = 2, expanded = false, has_children = false, badge = 'entry' }
62 │ w/TreeNode { id = 'pages.vk', label = 'pages.vk', depth = 2, expanded = false, has_children = false, badge = '' }
63 │ w/TreeNode { id = 'lib', label = 'lib/ui', depth = 1, expanded = true, has_children = true, badge = '29' }
64 │ w/TreeNode { id = 'ui/canvas.vk', label = 'canvas.vk', depth = 2, expanded = false, has_children = false, badge = 'RGBA' }
65 │ w/TreeNode { id = 'ui/font.vk', label = 'font.vk', depth = 2, expanded = false, has_children = false, badge = 'Aa' }
66 │ w/TreeNode { id = 'ui/layout.vk', label = 'layout.vk', depth = 2, expanded = false, has_children = false, badge = 'flex' }
67 │ w/TreeNode { id = 'ui/widgets.vk', label = 'widgets.vk', depth = 2, expanded = false, has_children = false, badge = 'active' }
68 │ w/TreeNode { id = 'image/png.vk', label = 'image/png.vk', depth = 1, expanded = false, has_children = false, badge = 'PNG' }
69 │ w/TreeNode { id = 'db/query.vk', label = 'db/query.vk', depth = 1, expanded = false, has_children = false, badge = 'IDX' }
70 │ w/TreeNode { id = 'tests', label = 'tests', depth = 1, expanded = false, has_children = true, badge = 'pass' }
71 │ ]
72 │ ]
73 │
74 │ pub sample-table-rows = fn [] block [
75 │ [
76 │ ['edge-gateway-01' 'Native x64' '28.5 KB' '0.31 ms' 'ONLINE']
77 │ ['wasm-sandbox-pool' 'Wasm 3.0' '64.0 KB' '0.58 ms' 'ACTIVE']
78 │ ['kv-primary-wal' 'Native x64' '41.2 KB' '0.24 ms' 'ONLINE']
79 │ ['otel-collector' 'VKO 64b VM' '19.8 KB' '0.79 ms' 'SYNCING']
80 │ ['pqc-kms-signer' 'ARM64 ELF' '34.0 KB' '0.44 ms' 'ONLINE']
81 │ ['regex-log-router' 'Native x64' '30.1 KB' '0.19 ms' 'PASS']
82 │ ]
83 │ ]
84 │
85 │ pub sample-audit-logs = fn [] block [
86 │ [
87 │ '12:04:01 [INFO] Tree-shook 14 unused stdlib fns (-685 KB)'
88 │ '12:04:02 [OK] Verified Ed25519 signature on pkg bundle'
89 │ '12:04:04 [SEC] Zeroized 64B .secret key buffer on scope exit'
90 │ '12:04:07 [NET] Reused keep-alive TCP stream (http://127.0.0.1)'
91 │ '12:04:09 [PNG] Encoded 960x600 RGBA32 frame via zlib + CRC32'
92 │ ]
93 │ ]demos/widget_gallery/src/pages.vk
1 │ // demos/widget_gallery/src/pages.vk
2 │ // 4 focused Light-Mode desktop views showcasing all 29 widgets in `lib/ui/widgets.vk`.
3 │
4 │ use [
5 │ cv = ui/canvas
6 │ fnt = ui/font
7 │ w = ui/widgets
8 │ m = model
9 │ ]
10 │
11 │ render-inputs-page = fn [mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, mut sec_buf secret bytes, area w/Rect, th w/Theme] [
12 │ cols = w/flex-row area [(w/flex 11) (w/flex 9)] 14
13 │ left = cols[0]
14 │ right = cols[1]
15 │
16 │ w/panel mut c left 'Form Inputs, Masked .secret & Code Editor' th
17 │ lb = w/panel-body left true 14
18 │
19 │ w/label mut c lb.x lb.y 'Cluster Service Endpoint (text-input)' 1 th.muted
20 │ ep_r = w/Rect { x = lb.x, y = lb.y + 16, w = lb.w, h = 28 }
21 │ put mut gm .endpoint (w/text-input mut c mut st 'inp-ep' ep_r gm.endpoint 'https://...' th)
22 │
23 │ w/label mut c lb.x (lb.y + 54) 'Hardware-Zeroized API Token (secret-input)' 1 th.muted
24 │ sec_r = w/Rect { x = lb.x, y = lb.y + 70, w = lb.w, h = 28 }
25 │ put mut gm .secret_len (w/secret-input mut c mut st 'inp-sec' sec_r mut sec_buf gm.secret_len 'Enter secret token...' th)
26 │
27 │ w/label mut c lb.x (lb.y + 108) 'Execution Track Target (dropdown)' 1 th.muted
28 │ dd_r = w/Rect { x = lb.x, y = lb.y + 124, w = lb.w, h = 28 }
29 │ tracks = ['Native x86_64 / ARM64 AOT' 'WebAssembly 3.0 Sandbox (vvm)' '64-bit ORO VKO Bytecode VM']
30 │ // Draw chip-group & text-area before open dropdown popup so popup layers cleanly if opened
31 │ w/label mut c lb.x (lb.y + 162) 'Workspace Capability Grants (chip-group)' 1 th.muted
32 │ cg_r = w/Rect { x = lb.x, y = lb.y + 178, w = lb.w, h = 26 }
33 │ toggled = w/chip-group mut c mut st 'chips-caps' cg_r ['.fs' '.clocks' '.net' '.ui' '.ffi'] gm.chip_flags th
34 │ if toggled >= 0 [
35 │ mut cf = gm.chip_flags
36 │ put mut cf toggled (not (cf[toggled] == true))
37 │ put mut gm .chip_flags cf
38 │ ]
39 │
40 │ w/label mut c lb.x (lb.y + 214) 'Syntax-Highlighted Veko Editor (code-editor, Ctrl+Z/Y)' 1 th.muted
41 │ ta_y = lb.y + 230
42 │ ta_h = (lb.y + lb.h) - ta_y
43 │ ta_r = w/Rect { x = lb.x, y = ta_y, w = lb.w, h = ta_h }
44 │ mut ed = gm.editor
45 │ _ = w/code-editor mut c mut st 'inp-code' ta_r mut ed th
46 │ put mut gm .editor ed
47 │
48 │ put mut gm .runtime_idx (w/dropdown mut c mut st 'dd-track' dd_r tracks gm.runtime_idx th)
49 │
50 │ // Right Card: Checkboxes, Switches, Radios, Slider, Progress, Primary/Secondary Buttons
51 │ w/panel mut c right 'Selection Controls, Sliders & Actions' th
52 │ rb = w/panel-body right true 14
53 │
54 │ w/heading mut c rb.x rb.y 'Compiler & Memory Guarantees' 1 th.text
55 │ put mut gm .chk_shake (w/checkbox mut c mut st 'chk-1' rb.x (rb.y + 20) 'Whole-program dead-function tree-shaking' gm.chk_shake th)
56 │ put mut gm .chk_strict (w/checkbox mut c mut st 'chk-2' rb.x (rb.y + 44) 'Enforce --strict-types & interface contracts' gm.chk_strict th)
57 │ put mut gm .chk_secret (w/checkbox mut c mut st 'chk-3' rb.x (rb.y + 68) 'Enforce .secret compile-time I/O firewall' gm.chk_secret th)
58 │
59 │ cv/fill-rect mut c rb.x (rb.y + 96) rb.w 1 th.border
60 │ put mut gm .sw_watch (w/toggle-switch mut c mut st 'sw-watch' rb.x (rb.y + 108) 'Live file watcher (veko run --watch)' gm.sw_watch th)
61 │ put mut gm .sw_audit (w/toggle-switch mut c mut st 'sw-audit' rb.x (rb.y + 134) 'Deterministic slab leak audit (--check-slabs)' gm.sw_audit th)
62 │
63 │ cv/fill-rect mut c rb.x (rb.y + 162) rb.w 1 th.border
64 │ w/heading mut c rb.x (rb.y + 172) 'Build Profile (radio-group)' 1 th.text
65 │ rg_r = w/Rect { x = rb.x, y = rb.y + 190, w = rb.w, h = 68 }
66 │ profiles = ['Release (Tree-Shaken Native PE32+/ELF64)' 'Zero-Trust Wasm 3.0 (Fuel & Cap Metered)' 'Interactive Debug (Source-Mapped Traces)']
67 │ put mut gm .opt_profile (w/radio-group mut c mut st 'rg-prof' rg_r profiles gm.opt_profile th)
68 │
69 │ w/label mut c rb.x (rb.y + 266) 'Worker Pool Threads (slider 1..32)' 1 th.muted
70 │ sl_r = w/Rect { x = rb.x, y = rb.y + 282, w = rb.w, h = 22 }
71 │ put mut gm .workers (w/slider mut c mut st 'sl-workers' sl_r gm.workers 1 32 th)
72 │
73 │ w/label mut c rb.x (rb.y + 312) 'Verification Suite Progress (progress-bar)' 1 th.muted
74 │ pb_r = w/Rect { x = rb.x, y = rb.y + 328, w = rb.w, h = 18 }
75 │ w/progress-bar/label mut c pb_r gm.progress_pct th true
76 │
77 │ btn_y = rb.y + rb.h - 30
78 │ btns = w/flex-row (w/Rect { x = rb.x, y = btn_y, w = rb.w, h = 30 }) [(w/flex 3) (w/flex 2)] 10
79 │ if w/button/primary mut c mut st 'btn-apply' btns[0] 'Apply Configuration' th true [
80 │ put mut gm .progress_pct (if gm.progress_pct >= 100 [ 60 ] else [ gm.progress_pct + 8 ])
81 │ put mut gm .status_text 'Applied workspace configuration and synced veko.vk capabilities'
82 │ ]
83 │ if w/button mut c mut st 'btn-reset' btns[1] 'Reset' th [
84 │ put mut gm .workers 12
85 │ put mut gm .progress_pct 84
86 │ put mut gm .status_text 'Restored default studio settings'
87 │ ]
88 │ .ok
89 │ ]
90 │
91 │ render-tables-page = fn [mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, area w/Rect, th w/Theme] [
92 │ cols = w/flex-row area [(w/px 268) (w/flex 1)] 14
93 │ left = cols[0]
94 │ right = cols[1]
95 │
96 │ w/panel mut c left 'Project Tree (tree-view)' th
97 │ tb = w/panel-body left true 10
98 │ put mut gm .selected_tree (w/tree-view mut c mut st 'tv-proj' tb (m/sample-tree) gm.selected_tree th)
99 │
100 │ r_rows = w/flex-col right [(w/flex 3) (w/flex 2)] 14
101 │ top_card = r_rows[0]
102 │ bot_card = r_rows[1]
103 │
104 │ w/panel mut c top_card 'Runtime Service Fleet & Capability Matrix (data-table)' th
105 │ dtb = w/panel-body top_card true 10
106 │ headers = ['Service Node' 'Execution Track' 'Binary' 'P99' 'Health']
107 │ tracks = [(w/flex 3) (w/flex 2) (w/px 74) (w/px 68) (w/px 86)]
108 │ put mut gm .selected_row (w/data-table mut c mut st 'dt-fleet' dtb headers tracks (m/sample-table-rows) gm.selected_row th)
109 │
110 │ w/panel mut c bot_card 'Scrollable Telemetry & Audit Stream (scroll-view + select-list)' th
111 │ bb = w/panel-body bot_card true 10
112 │ sub_cols = w/flex-row bb [(w/flex 3) (w/flex 2)] 12
113 │ put mut gm .selected_log (w/select-list mut c mut st 'lst-logs' sub_cols[0] (m/sample-audit-logs) gm.selected_log th)
114 │
115 │ // Scrollable inspector viewport on right
116 │ sc_r = sub_cols[1]
117 │ put mut gm .scroll_y (w/begin-scroll mut c mut st 'scr-insp' sc_r 190 gm.scroll_y th)
118 │ iy = sc_r.y + 8 - gm.scroll_y
119 │ ix = sc_r.x + 10
120 │ w/heading mut c ix iy 'Selected Node Inspector' 1 th.accent
121 │ rows_data = m/sample-table-rows
122 │ sel_r = rows_data[gm.selected_row]
123 │ w/label mut c ix (iy + 20) (str/join ['Node: ' (str/append '' sel_r[0])] '') 1 th.text
124 │ w/label mut c ix (iy + 38) (str/join ['Runtime: ' (str/append '' sel_r[1])] '') 1 th.text
125 │ w/label mut c ix (iy + 56) (str/join ['Size: ' (str/append '' sel_r[2])] '') 1 th.muted
126 │ w/label mut c ix (iy + 74) (str/join ['Latency: ' (str/append '' sel_r[3])] '') 1 th.muted
127 │ _ = w/badge mut c ix (iy + 94) 'ORO Single-Owner Verified' 'ok' th
128 │ w/label mut c ix (iy + 120) 'Tree Selection:' 1 th.muted
129 │ w/label mut c ix (iy + 136) gm.selected_tree 1 th.accent
130 │ w/end-scroll mut st mut c
131 │ .ok
132 │ ]
133 │
134 │ render-charts-page = fn [mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, area w/Rect, th w/Theme] [
135 │ rows = w/flex-col area [(w/px 74) (w/flex 1) (w/px 86)] 14
136 │ kpi_row = rows[0]
137 │ mid_row = rows[1]
138 │ bot_row = rows[2]
139 │
140 │ kpis = w/grid kpi_row 1 4 12
141 │ w/stat-card mut c kpis[0] 'HTTP/1.1 Keep-Alive' '148.2k/s' '+18.4%' 'ok' th
142 │ w/stat-card mut c kpis[1] 'Shaken PE32+ Size' '28.5 KB' '-94%' 'info' th
143 │ w/stat-card mut c kpis[2] 'P99 Tail Latency' '0.42 ms' '0 GC' 'ok' th
144 │ w/stat-card mut c kpis[3] 'Wasm Cache Hit' '1.8 ms' 'SHA256' 'warn' th
145 │
146 │ charts = w/flex-row mid_row [(w/flex 5) (w/flex 6)] 14
147 │ w/panel mut c charts[0] 'Throughput by Execution Track (bar-chart)' th
148 │ bcb = w/panel-body charts[0] true 12
149 │ w/bar-chart mut c bcb ['VM' 'Wasm' 'x64' 'ARM64' 'SIMD'] [64 128 246 238 292] th.accent th
150 │
151 │ w/panel mut c charts[1] 'Multi-Track Ops/ms Telemetry (line-chart)' th
152 │ lcb = w/panel-body charts[1] true 12
153 │ series = [
154 │ w/ChartSeries { name = 'Native AOT', values = [180 195 215 210 242 268], color = th.accent }
155 │ w/ChartSeries { name = 'Wasm 3.0', values = [110 124 132 140 152 166], color = th.success }
156 │ ]
157 │ w/line-chart mut c lcb ['00m' '10m' '20m' '30m' '40m' '50m'] series th
158 │
159 │ w/panel mut c bot_row 'Live Slab Allocation & Frame Pacing Sparklines (sparkline)' th
160 │ spb = w/panel-body bot_row true 8
161 │ sp_cols = w/grid spb 1 3 12
162 │ w/sparkline mut c sp_cols[0] [12 15 14 18 16 14 13 15 12 11 13 12] th.accent th
163 │ w/sparkline mut c sp_cols[1] [92 94 95 93 96 98 97 99 98 99 100 99] th.success th
164 │ w/sparkline mut c sp_cols[2] [28 24 22 19 21 18 16 15 17 14 13 12] th.warning th
165 │ .ok
166 │ ]
167 │
168 │ render-overlays-page = fn [mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, area w/Rect, th w/Theme] [
169 │ // Background mouse-draggable split-pane workspace (horizontal + nested vertical split)
170 │ sp_h = w/split-pane-state mut c mut st 'sp-main' area false gm.split_ratio th
171 │ put mut gm .split_ratio sp_h.ratio_pct
172 │ left_p = sp_h.first
173 │ right_p = sp_h.second
174 │
175 │ w/panel mut c left_p `Navigation Split Pane ({gm.split_ratio}%)` th
176 │ lb = w/panel-body left_p true 12
177 │ w/label mut c lb.x lb.y 'Right-click context menu & tooltip preview:' 1 th.muted
178 │ if gm.show_context [
179 │ ctx_items = [
180 │ ['Command Palette...' 'Ctrl+K']
181 │ ['Open Veko File...' 'Ctrl+O']
182 │ '-'
183 │ ['Run Doctests' 'Ctrl+T']
184 │ ['Export Light PNG' 'Ctrl+P']
185 │ ]
186 │ chit = w/context-menu mut c mut st 'ctx-demo' (lb.x + 8) (lb.y + 24) (lb.w - 16) ctx_items th
187 │ if chit == 0 [
188 │ mut ps0 = gm.palette
189 │ put mut ps0 .open true
190 │ put mut gm .palette ps0
191 │ ]
192 │ if chit == 1 [
193 │ mut fp0 = gm.picker
194 │ put mut fp0 .open true
195 │ put mut gm .picker fp0
196 │ ]
197 │ ]
198 │ w/tooltip mut c (lb.x + 8) (lb.y + lb.h - 28) 'Tip: Drag split divider or press Tab' th
199 │
200 │ sp_v = w/split-pane-state mut c mut st 'sp-right' right_p true gm.vsplit_ratio th
201 │ put mut gm .vsplit_ratio sp_v.ratio_pct
202 │ w/panel mut c sp_v.first 'Primary Editor Canvas (split-pane top)' th
203 │ tb = w/panel-body sp_v.first true 12
204 │ w/label mut c tb.x tb.y 'Active Package: veko-ui-gallery v1.0.0 (Ed25519 Signed)' 1 th.text
205 │ _ = w/badge mut c tb.x (tb.y + 22) 'CAPABILITIES: .fs .clocks .env .ui' 'info' th
206 │
207 │ w/panel mut c sp_v.second 'Output & Notification Tray (split-pane bottom)' th
208 │ bb = w/panel-body sp_v.second true 12
209 │ w/label mut c bb.x bb.y 'Build status: 0 errors, 0 warnings across 3 tracks.' 1 th.success
210 │
211 │ // Centered modal lightbox dialog over the right split pane
212 │ if gm.show_modal [
213 │ md = w/modal mut c mut st 'mdl-sign' right_p 390 210 'Publish Signed VKP1 Package' th
214 │ if md.closed == true [ put mut gm .show_modal false ]
215 │ mb = md.body
216 │ w/label mut c mb.x mb.y 'Bundle: dist/widget-gallery-1.0.0.vkp' 1 th.text
217 │ w/label mut c mb.x (mb.y + 20) 'Signer: ed25519:9f84c2a1...7b3e0d12' 1 th.muted
218 │ _ = w/badge mut c mb.x (mb.y + 42) 'Deterministic Reproducible Archive' 'ok' th
219 │ mbtns = w/flex-row (w/Rect { x = mb.x, y = mb.y + mb.h - 30, w = mb.w, h = 28 }) [(w/flex 1) (w/flex 1)] 10
220 │ if w/button/primary mut c mut st 'mdl-ok' mbtns[0] 'Sign & Publish' th true [
221 │ put mut gm .status_text 'Signed VKP1 bundle with Ed25519 key'
222 │ ]
223 │ if w/button mut c mut st 'mdl-cancel' mbtns[1] 'Dismiss' th [
224 │ put mut gm .show_modal false
225 │ ]
226 │ ]
227 │
228 │ // Non-blocking bottom-right toast notification
229 │ toast_r = w/Rect { x = area.x + area.w - 336, y = area.y + area.h - 54, w = 328, h = 46 }
230 │ w/toast mut c toast_r 'PNG Capture Ready' 'Rendered crisp Light-Mode RGBA32 surface' 'ok' th
231 │ .ok
232 │ ]
233 │
234 │ // Renders a complete `960x600` desktop frame of the Veko Studio Widget Gallery.
235 │ pub render-gallery = fn [mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, mut sec_buf secret bytes] [
236 │ th = if gm.dark_mode [ w/dark-theme ] else [ w/light-theme ]
237 │ cv/clear mut c th.bg
238 │
239 │ // Top application menu bar (full width, 30px)
240 │ menu_r = w/Rect { x = 0, y = 0, w = c.width, h = 30 }
241 │ mhit = w/menu-bar mut c mut st 'top-menu' menu_r 'Veko Studio' ['Workspace' 'Widgets' 'Layout' 'Docs' 'Help'] gm.active_menu th
242 │ if mhit >= 0 [ put mut gm .active_menu mhit ]
243 │
244 │ // Header toolbar with icon buttons & theme toggle on right side of menu bar
245 │ ib_search = w/Rect { x = c.width - 238, y = 4, w = 24, h = 22 }
246 │ ib_folder = w/Rect { x = c.width - 210, y = 4, w = 24, h = 22 }
247 │ ib_refresh = w/Rect { x = c.width - 182, y = 4, w = 24, h = 22 }
248 │ ib_play = w/Rect { x = c.width - 154, y = 4, w = 24, h = 22 }
249 │ if w/icon-button mut c mut st 'ib-s' ib_search 'search' th [
250 │ mut ps_open = gm.palette
251 │ put mut ps_open .open (not ps_open.open)
252 │ put mut gm .palette ps_open
253 │ ]
254 │ if w/icon-button mut c mut st 'ib-f' ib_folder 'folder' th [
255 │ mut fp_open = gm.picker
256 │ put mut fp_open .open (not fp_open.open)
257 │ put mut gm .picker fp_open
258 │ ]
259 │ _ = w/icon-button mut c mut st 'ib-r' ib_refresh 'refresh' th
260 │ _ = w/icon-button mut c mut st 'ib-p' ib_play 'play' th
261 │ mode_lbl = if gm.dark_mode [ 'Dark Mode' ] else [ 'Light Mode' ]
262 │ if w/button mut c mut st 'btn-theme' (w/Rect { x = c.width - 122, y = 4, w = 110, h = 22 }) mode_lbl th [
263 │ put mut gm .dark_mode (not gm.dark_mode)
264 │ ]
265 │
266 │ // Main workspace container below menu bar
267 │ outer = w/Rect { x = 16, y = 42, w = c.width - 32, h = c.height - 54 }
268 │ shell = w/flex-col outer [(w/px 34) (w/flex 1) (w/px 28)] 12
269 │
270 │ // 4-view tab bar
271 │ tab_labels = [
272 │ '1. Inputs & Code Editor'
273 │ '2. Data Tables & Trees'
274 │ '3. KPI Cards & Charts'
275 │ '4. Split Panes & Overlays'
276 │ ]
277 │ put mut gm .active_tab (w/tabs mut c mut st 'nav-tabs' shell[0] tab_labels gm.active_tab th)
278 │
279 │ // Active page body
280 │ body = shell[1]
281 │ if gm.active_tab == 0 [ render-inputs-page mut c mut st mut gm mut sec_buf body th ]
282 │ if gm.active_tab == 1 [ render-tables-page mut c mut st mut gm body th ]
283 │ if gm.active_tab == 2 [ render-charts-page mut c mut st mut gm body th ]
284 │ if gm.active_tab == 3 [ render-overlays-page mut c mut st mut gm body th ]
285 │
286 │ // Studio Command Palette & File Picker overlays (active when toggled via toolbar or Ctrl+K / Ctrl+O)
287 │ full_vp = w/Rect { x = 0, y = 0, w = c.width, h = c.height }
288 │ mut pal = gm.palette
289 │ cmd_id = w/command-palette mut c mut st 'pal' full_vp mut pal (m/sample-commands) th
290 │ put mut gm .palette pal
291 │ if cmd_id == 'toggle-theme' [ put mut gm .dark_mode (not gm.dark_mode) ]
292 │ if cmd_id == 'open-file' [
293 │ mut fp1 = gm.picker
294 │ put mut fp1 .open true
295 │ put mut gm .picker fp1
296 │ ]
297 │ if cmd_id == 'tab-inputs' [ put mut gm .active_tab 0 ]
298 │ if cmd_id == 'tab-tables' [ put mut gm .active_tab 1 ]
299 │ if cmd_id == 'tab-charts' [ put mut gm .active_tab 2 ]
300 │ if cmd_id == 'tab-overlays' [ put mut gm .active_tab 3 ]
301 │
302 │ mut pk = gm.picker
303 │ pk_res = w/file-picker mut c mut st 'fp' full_vp mut pk (m/sample-files) th
304 │ put mut gm .picker pk
305 │ if pk_res.action == .selected [
306 │ put mut gm .status_text `Selected workspace file: {pk_res.path}`
307 │ ]
308 │
309 │ // Bottom status bar with Hi-DPI & Clipboard status badges
310 │ ftr = shell[2]
311 │ cv/fill-rounded-rect mut c ftr.x ftr.y ftr.w ftr.h 5 th.surface
312 │ cv/stroke-rounded-rect mut c ftr.x ftr.y ftr.w ftr.h 5 th.border
313 │ fnt/draw-text mut c (ftr.x + 12) (ftr.y + 10) gm.status_text 1 th.muted
314 │ dpi_lbl = `Hi-DPI {st.dpi_scale}%`
315 │ _ = w/badge mut c (ftr.x + ftr.w - 224) (ftr.y + 5) dpi_lbl 'info' th
316 │ _ = w/badge mut c (ftr.x + ftr.w - 118) (ftr.y + 5) '960x600 RGBA32' 'neutral' th
317 │ .ok
318 │ ]demos/widget_gallery/src/main.vk
1 │ // demos/widget_gallery/src/main.vk
2 │ // Veko Studio UI Widget Gallery — Showcases 29 pure-Veko immediate-mode widgets, flex/grid/split
3 │ // layouts, `.secret` masked inputs, charts, and deterministic Light-Mode PNG screenshot export.
4 │ // - Default mode: renders & verifies all 4 Light-Mode pages (`--export-dir <dir>` writes PNGs)
5 │ // - Interactive OS window mode: `veko demos/widget_gallery -- --live`
6 │
7 │ use [
8 │ ui
9 │ cv = ui/canvas
10 │ png = image/png
11 │ w = ui/widgets
12 │ m = model
13 │ pg = pages
14 │ ]
15 │
16 │ find-flag-val = fn [argv block, flag str] str [
17 │ mut i = 0
18 │ while i < (len argv) [
19 │ a = str/append '' argv[i]
20 │ if a == flag and (i + 1) < (len argv) [
21 │ return (str/append '' argv[i + 1])
22 │ ]
23 │ i = i + 1
24 │ ]
25 │ ''
26 │ ]
27 │
28 │ has-arg? = fn [argv block, flag str] bool [
29 │ mut i = 0
30 │ while i < (len argv) [
31 │ if (str/append '' argv[i]) == flag [ return true ]
32 │ i = i + 1
33 │ ]
34 │ false
35 │ ]
36 │
37 │ run-live = fn [win ui/Window, mut c cv/Canvas, mut st w/UiState, mut gm m/GalleryModel, mut sec_buf secret bytes] [
38 │ put mut st .dpi_scale (ui/window-dpi-scale win)
39 │ mut running = true
40 │ while running [
41 │ evs = ui/poll win
42 │ if w/apply-events mut st evs [ running = false ]
43 │ if st.key_code == 27 [ running = false ]
44 │ if st.text_char == 22 [
45 │ put mut st .clipboard (ui/clipboard-text)
46 │ ]
47 │ pg/render-gallery mut c mut st mut gm mut sec_buf
48 │ if st.clipboard_dirty [
49 │ _ = ui/set-clipboard st.clipboard
50 │ put mut st .clipboard_dirty false
51 │ ]
52 │ _ = ui/present-canvas win c
53 │ time/sleep 16ms
54 │ ]
55 │ .ok
56 │ ]
57 │
58 │ main = fn [] any [
59 │ cw = 960
60 │ ch = 600
61 │ mut c = cv/new-canvas cw ch
62 │ mut st = w/new-state
63 │ mut gm = m/GalleryModel {}
64 │ mut sec_buf = bytes/with-secret 32
65 │ mut k = 0
66 │ while k < 16 [
67 │ _ = bytes/push mut sec_buf 42
68 │ k = k + 1
69 │ ]
70 │
71 │ argv = os/args
72 │ export_dir = find-flag-val argv '--export-dir'
73 │
74 │ win = ui/open-window 'Veko Studio — UI Widget Gallery' cw ch
75 │ if (has-arg? argv '--live') and ((os/getenv/or 'VEKO_HEADLESS' ['']) != '1') [
76 │ run-live win mut c mut st mut gm mut sec_buf
77 │ _ = ui/close-window win
78 │ return .ok
79 │ ]
80 │
81 │ if export_dir != '' [
82 │ _ = os/mkdir/or export_dir [.ok]
83 │ ]
84 │
85 │ filenames = [
86 │ 'widget_gallery_inputs.png'
87 │ 'widget_gallery_tables.png'
88 │ 'widget_gallery_charts.png'
89 │ 'widget_gallery_overlays.png'
90 │ ]
91 │
92 │ mut total_png_bytes = 0
93 │ mut tab = 0
94 │ while tab < 4 [
95 │ put mut gm .active_tab tab
96 │ put mut gm .dark_mode false
97 │ put mut gm .show_modal true
98 │ // Focus endpoint input on page 0 to show active focus ring + caret
99 │ put mut st .focused_id (if tab == 0 [ 'inp-ep' ] else [ '' ])
100 │ w/apply-mouse mut st -1 -1 false false
101 │ pg/render-gallery mut c mut st mut gm mut sec_buf
102 │ _ = ui/present-canvas win c
103 │
104 │ // Verify crisp Light-Mode background pixel
105 │ bg_px = cv/get-pixel c 8 50
106 │ if bg_px.r < 220 or bg_px.g < 225 or bg_px.b < 230 [
107 │ _ = ui/close-window win
108 │ return (err 'widget_gallery: expected crisp Light-Mode background surface')
109 │ ]
110 │
111 │ if export_dir != '' [
112 │ png_data = png/encode c
113 │ if png_data[0] != 137 or png_data[1] != 80 or png_data[2] != 78 or png_data[3] != 71 [
114 │ _ = ui/close-window win
115 │ return (err 'widget_gallery: invalid PNG signature')
116 │ ]
117 │ total_png_bytes = total_png_bytes + (len png_data)
118 │ out_file = str/join [export_dir '/' filenames[tab]] ''
119 │ _ = os/write-file/or out_file png_data [e -> return e]
120 │ ] else [
121 │ if tab == 0 [
122 │ // Fast lossless PNG verification on a 160x100 viewport tile during cross-track test runs
123 │ mut tile = cv/new-canvas 160 100
124 │ mut ty = 0
125 │ while ty < 100 [
126 │ mut tx = 0
127 │ while tx < 160 [
128 │ cv/set-pixel mut tile tx ty (cv/get-pixel c tx ty)
129 │ tx = tx + 1
130 │ ]
131 │ ty = ty + 1
132 │ ]
133 │ png_tile = png/encode tile
134 │ if png_tile[0] != 137 or png_tile[1] != 80 [
135 │ _ = ui/close-window win
136 │ return (err 'widget_gallery: invalid PNG tile signature')
137 │ ]
138 │ total_png_bytes = len png_tile
139 │ ]
140 │ ]
141 │ tab = tab + 1
142 │ ]
143 │
144 │ if export_dir != '' [
145 │ // Export 5th screenshot showcasing Ctrl+A selection highlight, OS Clipboard sync & Hi-DPI scaling
146 │ put mut gm .active_tab 0
147 │ put mut gm .dark_mode false
148 │ put mut gm .status_text 'Clipboard copied (Ctrl+A / Ctrl+C): https://edge.veko.dev:8443 • Win32 & Zero-libc X11 Ready'
149 │ put mut st .focused_id 'inp-ep'
150 │ put mut st .selected_id 'inp-ep'
151 │ put mut st .dpi_scale 150
152 │ _ = ui/set-clipboard gm.endpoint
153 │ put mut st .clipboard (ui/clipboard-text)
154 │ pg/render-gallery mut c mut st mut gm mut sec_buf
155 │ png_cb = png/encode c
156 │ total_png_bytes = total_png_bytes + (len png_cb)
157 │ _ = os/write-file/or (str/join [export_dir '/widget_gallery_clipboard_hidpi.png'] '') png_cb [e -> return e]
158 │ ]
159 │
160 │ _ = ui/close-window win
161 │ println `[Widget Gallery] 960x600 pages=4 widgets=29 theme=light png_total={total_png_bytes}B`
162 │ .ok
163 │ ]
164 │
165 │ res = main
166 │ if err? res [
167 │ println (str/append 'FAIL: ' (mold res))
168 │ os/exit 1
169 │ ]Showcase 2: Canvas Workbench — Interactive 4-Tab Native Desktop GUI (demos/canvas_workbench/)
Canvas Workbench is a multi-module native desktop GUI application built with pure-Veko immediate-mode graphics (lib/ui/canvas.vk, lib/ui/widgets.vk, lib/ui.vk) and embedded persistence (lib/db/kv.vk).
Highlights
- Light-First Dual-Theme Desktop UI: Opens in a crisp daylight palette (
w/light-theme) with a live 1-clickTHEME: LIGHT / DARKbutton (Tkey). - Four Interactive Workspace Tabs (
1..4):- Cluster Topology: Interactive clickable service nodes, animated link packet pulses, availability progress bars, and
w/sparklinelatency plots. - Sketch Pad: Interactive mouse drawing canvas with 5 color swatches and 3 brush widths (
2PX,4PX,7PX). - Durable Sprint Board: Scrollable
w/list-viewpersisted atomically to a localdb/kvWAL store. - Runtime & Crypto Profiler: Zero-copy
mut cv.pixels(rc == 1) frame counter, pure-VekoSHA-256+CRC-32benchmark runner, and 24-bit.bmpscreenshot exporter.
- Cluster Topology: Interactive clickable service nodes, animated link packet pulses, availability progress bars, and
Running Across All Runtimes
veko check --strict-types demos/canvas_workbench/src/main.vk
veko run demos/canvas_workbench/src/main.vk
veko run --wasm --fuel=0 --allow-fs --check-slabs demos/canvas_workbench/src/main.vk
veko run --native demos/canvas_workbench/src/main.vk
veko run --native demos/canvas_workbench/src/main.vk -- --live
veko compile --native --gui demos/canvas_workbench/src/main.vk -o dist/canvas_workbench.exe
Complete Module Listings
demos/canvas_workbench/veko.vk
{
name = 'canvas_workbench'
root = 'src'
allow-caps = [.fs .clocks .env .ui]
}demos/canvas_workbench/src/state.vk
1 │ // demos/canvas_workbench/src/state.vk
2 │ // Application state & `db/kv` task persistence for Canvas Workbench.
3 │
4 │ use [
5 │ kv = db/kv
6 │ sha = crypto/sha256
7 │ bits
8 │ ]
9 │
10 │ pub AppModel = struct {
11 │ active_tab i64 = 0
12 │ dark_mode bool = false
13 │ selected_node i64 = 0
14 │ pulse_tick i64 = 0
15 │ brush_radius i64 = 3
16 │ swatch_idx i64 = 0
17 │ strokes block = []
18 │ tasks block = []
19 │ selected_task i64 = 0
20 │ sha_rounds i64 = 64
21 │ last_crc_hex str = '0x00000000'
22 │ status_msg str = 'Ready — Click tabs 1..4 or press T for theme'
23 │ }
24 │
25 │ pub load-persisted-tasks = fn [db_path str] block [
26 │ if not (os/exists? db_path) [
27 │ return [
28 │ '[DONE] Ship ORO 16B Value Arena'
29 │ '[DONE] Verify S1 == S2 ARM64 ELF64'
30 │ '[OPEN] Tune RGBA32 Zero-Copy Canvas'
31 │ '[OPEN] Publish Veko 1.0 EPUB Guide'
32 │ ]
33 │ ]
34 │ mut db = kv/open-fast db_path
35 │ if not (kv/has? db 'workbench:tasks') [
36 │ _ = kv/close mut db
37 │ return [
38 │ '[DONE] Ship ORO 16B Value Arena'
39 │ '[OPEN] Tune RGBA32 Zero-Copy Canvas'
40 │ ]
41 │ ]
42 │ dec = kv/get-val db 'workbench:tasks'
43 │ _ = kv/close mut db
44 │ if err? dec [ return [] ]
45 │ if (type-of dec) != .block [ return [] ]
46 │ mut out = []
47 │ mut i = 0
48 │ while i < (len dec) [
49 │ push mut out (str/append '' dec[i])
50 │ i = i + 1
51 │ ]
52 │ out
53 │ ]
54 │
55 │ pub save-persisted-tasks = fn [db_path str, tasks block] [
56 │ mut db = kv/open-fast db_path
57 │ _ = kv/put-val mut db 'workbench:tasks' tasks
58 │ _ = kv/close mut db
59 │ .ok
60 │ ]
61 │
62 │ pub run-crypto-bench-step = fn [mut m AppModel] [
63 │ payload = bytes/from-str 'veko-1.0-canvas-workbench-zero-copy-frame'
64 │ mut digest = sha/sha256 payload
65 │ mut r = 1
66 │ while r < 16 [
67 │ digest = sha/sha256 digest
68 │ r = r + 1
69 │ ]
70 │ crc = bits/crc32 digest
71 │ put mut m .sha_rounds (m.sha_rounds + 16)
72 │ put mut m .last_crc_hex (mold crc)
73 │ put mut m .status_msg (str/join ['Hashed ' (mold m.sha_rounds) ' SHA-256 rounds (CRC=' (mold crc) ')'] '')
74 │ .ok
75 │ ]demos/canvas_workbench/src/views.vk
1 │ // demos/canvas_workbench/src/views.vk
2 │ // Immediate-mode 4-tab desktop workspace renderer built on `ui/canvas` and `ui/widgets`.
3 │
4 │ use [
5 │ cv = ui/canvas
6 │ w = ui/widgets
7 │ st = state
8 │ ]
9 │
10 │ swatch-color = fn [idx i64] cv/Color [
11 │ if idx == 0 [ return (cv/rgb 2 132 199) ]
12 │ if idx == 1 [ return (cv/rgb 5 150 105) ]
13 │ if idx == 2 [ return (cv/rgb 217 119 6) ]
14 │ if idx == 3 [ return (cv/rgb 225 29 72) ]
15 │ cv/rgb 124 58 237
16 │ ]
17 │
18 │ render-topology-tab = fn [mut c cv/Canvas, mut ui_st w/UiState, mut m st/AppModel, body w/Rect, th w/Theme] [
19 │ cols = w/hstack body [436 250] 10
20 │ left = cols[0]
21 │ right = cols[1]
22 │
23 │ w/panel mut c left 'CLUSTER TOPOLOGY & SIGNAL MESH' th
24 │ // Interactive cluster node coordinates relative to `left`
25 │ nx0 = left.x + 76
26 │ ny0 = left.y + 88
27 │ nx1 = left.x + 218
28 │ ny1 = left.y + 68
29 │ nx2 = left.x + 356
30 │ ny2 = left.y + 104
31 │ nx3 = left.x + 218
32 │ ny3 = left.y + 206
33 │
34 │ // Packet link conduits
35 │ cv/draw-line mut c nx0 ny0 nx1 ny1 th.accent
36 │ cv/draw-line mut c nx1 ny1 nx2 ny2 th.accent
37 │ cv/draw-line mut c nx0 ny0 nx3 ny3 th.success
38 │ cv/draw-line mut c nx2 ny2 nx3 ny3 th.success
39 │
40 │ // Animated packet pulse along active link
41 │ phase = (m.pulse_tick % 20)
42 │ px = nx0 + ((nx1 - nx0) * phase) / 20
43 │ py = ny0 + ((ny1 - ny0) * phase) / 20
44 │ cv/fill-circle mut c px py 4 th.warning
45 │
46 │ nodes_xy = [[nx0 ny0 'EDGE-GW'] [nx1 ny1 'REACTOR'] [nx2 ny2 'KV-WAL'] [nx3 ny3 'PQC-KMS']]
47 │ mut i = 0
48 │ while i < 4 [
49 │ nd = nodes_xy[i]
50 │ cx = as-i64 nd[0]
51 │ cy = as-i64 nd[1]
52 │ nm = str/append '' nd[2]
53 │ hit_r = w/Rect { x = (cx - 28), y = (cy - 22), w = 56, h = 44 }
54 │ if ui_st.mouse_clicked and (w/rect-contains? hit_r ui_st.mouse_x ui_st.mouse_y) [
55 │ put mut m .selected_node i
56 │ put mut m .status_msg (str/append 'Selected cluster node: ' nm)
57 │ ]
58 │ sel = m.selected_node == i
59 │ cv/fill-circle mut c cx cy (if sel [ 22 ] else [ 18 ]) (if sel [ th.accent ] else [ th.surface_hover ])
60 │ cv/fill-circle mut c cx cy 12 (if sel [ th.success ] else [ th.accent ])
61 │ w/label mut c (cx - 22) (cy + 26) nm 1 th.text
62 │ i = i + 1
63 │ ]
64 │
65 │ btn_pulse = w/Rect { x = (left.x + 14), y = (left.y + left.h - 36), w = 136, h = 26 }
66 │ if w/button mut c mut ui_st 'step-pulse' btn_pulse 'ADVANCE PULSE' th [
67 │ put mut m .pulse_tick (m.pulse_tick + 3)
68 │ put mut m .status_msg 'Advanced mesh packet telemetry window'
69 │ ]
70 │
71 │ r_rows = w/vstack right [148 164] 10
72 │ w/panel mut c r_rows[0] 'NODE HEALTH & LOAD' th
73 │ names = ['EDGE-GW (HTTP/2)' 'REACTOR (EPOLL)' 'KV-WAL (CRC32)' 'PQC-KMS (ML-KEM)']
74 │ loads = [88 94 99 96]
75 │ sel_idx = m.selected_node
76 │ w/label mut c (r_rows[0].x + 12) (r_rows[0].y + 32) (str/append '' names[sel_idx]) 1 th.text
77 │ w/label mut c (r_rows[0].x + 12) (r_rows[0].y + 52) 'SLO Availability:' 1 th.muted
78 │ w/progress-bar mut c (w/Rect { x = (r_rows[0].x + 12), y = (r_rows[0].y + 68), w = (r_rows[0].w - 24), h = 16 }) (as-i64 loads[sel_idx]) th
79 │ w/label mut c (r_rows[0].x + 12) (r_rows[0].y + 98) (str/join ['Pulse Tick: #' (mold m.pulse_tick)] '') 1 th.muted
80 │
81 │ w/panel mut c r_rows[1] 'P99 LATENCY (US)' th
82 │ base_l = 12 + (m.pulse_tick % 7)
83 │ lats = [14 18 15 21 16 19 24 17 15 base_l (base_l + 4) 16]
84 │ w/sparkline mut c (w/Rect { x = (r_rows[1].x + 12), y = (r_rows[1].y + 32), w = (r_rows[1].w - 24), h = 92 }) lats th.accent th
85 │ w/label mut c (r_rows[1].x + 12) (r_rows[1].y + 136) 'Zero GC pauses across all frames' 1 th.success
86 │ .ok
87 │ ]
88 │
89 │ render-paint-tab = fn [mut c cv/Canvas, mut ui_st w/UiState, mut m st/AppModel, body w/Rect, th w/Theme] [
90 │ cols = w/hstack body [486 200] 10
91 │ pad_box = cols[0]
92 │ tools = cols[1]
93 │
94 │ w/panel mut c pad_box 'VECTOR & PIXEL SKETCH PAD (CLICK TO DRAW)' th
95 │ inner = w/Rect { x = (pad_box.x + 10), y = (pad_box.y + 28), w = (pad_box.w - 20), h = (pad_box.h - 38) }
96 │ cv/fill-rect mut c inner.x inner.y inner.w inner.h th.bg
97 │ cv/stroke-rect mut c inner.x inner.y inner.w inner.h 1 th.border
98 │
99 │ // Record new brush point when mouse is pressed inside pad
100 │ if ui_st.mouse_down and (w/rect-contains? inner ui_st.mouse_x ui_st.mouse_y) [
101 │ mut next_s = m.strokes
102 │ if (len next_s) < 256 [
103 │ push mut next_s [ui_st.mouse_x ui_st.mouse_y m.brush_radius m.swatch_idx]
104 │ put mut m .strokes next_s
105 │ ]
106 │ ]
107 │
108 │ // Seed clean geometric preview motif + user strokes
109 │ cv/draw-line mut c (inner.x + 28) (inner.y + 180) (inner.x + 160) (inner.y + 64) th.accent
110 │ cv/draw-line mut c (inner.x + 160) (inner.y + 64) (inner.x + 310) (inner.y + 150) th.success
111 │ cv/fill-circle mut c (inner.x + 160) (inner.y + 64) 10 th.accent
112 │
113 │ mut si = 0
114 │ strokes = m.strokes
115 │ while si < (len strokes) [
116 │ pt = strokes[si]
117 │ cv/fill-circle mut c (as-i64 pt[0]) (as-i64 pt[1]) (as-i64 pt[2]) (swatch-color (as-i64 pt[3]))
118 │ si = si + 1
119 │ ]
120 │
121 │ w/panel mut c tools 'BRUSH & SWATCHES' th
122 │ mut sw = 0
123 │ while sw < 5 [
124 │ sr = w/Rect { x = (tools.x + 12 + sw * 36), y = (tools.y + 34), w = 28, h = 24 }
125 │ cv/fill-rounded-rect mut c sr.x sr.y sr.w sr.h 4 (swatch-color sw)
126 │ if m.swatch_idx == sw [
127 │ cv/stroke-rect mut c (sr.x - 1) (sr.y - 1) (sr.w + 2) (sr.h + 2) 1 th.text
128 │ ]
129 │ if ui_st.mouse_clicked and (w/rect-contains? sr ui_st.mouse_x ui_st.mouse_y) [
130 │ put mut m .swatch_idx sw
131 │ put mut m .status_msg (str/join ['Selected color swatch #' (mold (sw + 1))] '')
132 │ ]
133 │ sw = sw + 1
134 │ ]
135 │
136 │ if w/button mut c mut ui_st 'br-sm' (w/Rect { x = (tools.x + 12), y = (tools.y + 74), w = 52, h = 24 }) '2PX' th [
137 │ put mut m .brush_radius 2
138 │ ]
139 │ if w/button mut c mut ui_st 'br-md' (w/Rect { x = (tools.x + 74), y = (tools.y + 74), w = 52, h = 24 }) '4PX' th [
140 │ put mut m .brush_radius 4
141 │ ]
142 │ if w/button mut c mut ui_st 'br-lg' (w/Rect { x = (tools.x + 136), y = (tools.y + 74), w = 52, h = 24 }) '7PX' th [
143 │ put mut m .brush_radius 7
144 │ ]
145 │ if w/button mut c mut ui_st 'clear-pad' (w/Rect { x = (tools.x + 12), y = (tools.y + 112), w = 176, h = 26 }) 'CLEAR STROKES' th [
146 │ put mut m .strokes []
147 │ put mut m .status_msg 'Cleared sketch pad strokes'
148 │ ]
149 │ w/label mut c (tools.x + 12) (tools.y + 156) (str/join ['Strokes: ' (mold (len m.strokes))] '') 1 th.text
150 │ w/label mut c (tools.x + 12) (tools.y + 174) (str/join ['Cursor: ' (mold ui_st.mouse_x) ',' (mold ui_st.mouse_y)] '') 1 th.muted
151 │ .ok
152 │ ]
153 │
154 │ render-tasks-tab = fn [mut c cv/Canvas, mut ui_st w/UiState, mut m st/AppModel, db_path str, body w/Rect, th w/Theme] [
155 │ cols = w/hstack body [466 220] 10
156 │ list_box = cols[0]
157 │ act_box = cols[1]
158 │
159 │ w/panel mut c list_box 'DURABLE SPRINT BOARD (BACKED BY DB/KV)' th
160 │ lv_rect = w/Rect { x = (list_box.x + 12), y = (list_box.y + 30), w = (list_box.w - 24), h = (list_box.h - 42) }
161 │ w/list-view mut c lv_rect m.tasks m.selected_task th
162 │
163 │ // Click selection inside list-view rows
164 │ if ui_st.mouse_clicked and (w/rect-contains? lv_rect ui_st.mouse_x ui_st.mouse_y) [
165 │ idx = (ui_st.mouse_y - (lv_rect.y + 4)) / 16
166 │ if idx >= 0 and idx < (len m.tasks) [
167 │ put mut m .selected_task idx
168 │ ]
169 │ ]
170 │
171 │ w/panel mut c act_box 'WORKFLOW ACTIONS' th
172 │ if w/button mut c mut ui_st 'task-next' (w/Rect { x = (act_box.x + 14), y = (act_box.y + 36), w = 192, h = 26 }) 'SELECT NEXT ITEM' th [
173 │ n = len m.tasks
174 │ if n > 0 [ put mut m .selected_task ((m.selected_task + 1) % n) ]
175 │ ]
176 │ if w/button mut c mut ui_st 'task-done' (w/Rect { x = (act_box.x + 14), y = (act_box.y + 72), w = 192, h = 26 }) 'MARK SELECTED DONE' th [
177 │ mut ts = m.tasks
178 │ idx = m.selected_task
179 │ if idx >= 0 and idx < (len ts) [
180 │ cur = str/append '' ts[idx]
181 │ if str/contains? cur '[OPEN] ' [
182 │ updated = str/append '[DONE] ' cur[7..(len cur)]
183 │ put mut ts idx updated
184 │ put mut m .tasks ts
185 │ st/save-persisted-tasks db_path ts
186 │ put mut m .status_msg 'Persisted [DONE] state to db/kv WAL'
187 │ ]
188 │ ]
189 │ ]
190 │ if w/button mut c mut ui_st 'task-add' (w/Rect { x = (act_box.x + 14), y = (act_box.y + 108), w = 192, h = 26 }) '+ ADD SPRINT TASK' th [
191 │ mut ts = m.tasks
192 │ push mut ts (str/join ['[OPEN] Milestone Task #' (mold ((len ts) + 1))] '')
193 │ put mut m .tasks ts
194 │ st/save-persisted-tasks db_path ts
195 │ put mut m .status_msg 'Appended new durable task to db/kv'
196 │ ]
197 │
198 │ mut done_cnt = 0
199 │ mut ti = 0
200 │ while ti < (len m.tasks) [
201 │ if str/contains? (str/append '' m.tasks[ti]) '[DONE]' [ done_cnt = done_cnt + 1 ]
202 │ ti = ti + 1
203 │ ]
204 │ pct = if (len m.tasks) > 0 [ (done_cnt * 100) / (len m.tasks) ] else [ 0 ]
205 │ w/label mut c (act_box.x + 14) (act_box.y + 158) (str/join ['Completion: ' (mold pct) '%'] '') 1 th.text
206 │ w/progress-bar mut c (w/Rect { x = (act_box.x + 14), y = (act_box.y + 176), w = 192, h = 16 }) pct th
207 │ .ok
208 │ ]
209 │
210 │ render-bench-tab = fn [mut c cv/Canvas, mut ui_st w/UiState, mut m st/AppModel, bmp_path str, body w/Rect, th w/Theme] [
211 │ w/panel mut c body 'RUNTIME & ZERO-COPY FRAMEBUFFER PROFILER' th
212 │ bx = body.x + 18
213 │ by = body.y + 36
214 │ w/label mut c bx by 'Pixel Buffer Ownership: mut cv.pixels (rc == 1, 0 CoW copies/frame)' 1 th.success
215 │ w/label mut c bx (by + 22) (str/join ['Pure-Veko SHA-256 Rounds Executed: ' (mold m.sha_rounds)] '') 1 th.text
216 │ w/label mut c bx (by + 42) (str/join ['Last Digest CRC-32 Checksum: ' m.last_crc_hex] '') 1 th.muted
217 │
218 │ w/label mut c bx (by + 74) 'Throughput Index (ORO Zero-Copy):' 1 th.text
219 │ w/progress-bar mut c (w/Rect { x = bx, y = (by + 90), w = 420, h = 18 }) 96 th
220 │
221 │ if w/button mut c mut ui_st 'run-sha' (w/Rect { x = bx, y = (by + 128), w = 190, h = 28 }) 'RUN +16 SHA-256 ROUNDS' th [
222 │ st/run-crypto-bench-step mut m
223 │ ]
224 │ if w/button mut c mut ui_st 'save-bmp' (w/Rect { x = (bx + 206), y = (by + 128), w = 190, h = 28 }) 'EXPORT BMP SCREENSHOT' th [
225 │ bmp = cv/encode-bmp c
226 │ _ = os/write-file bmp_path bmp
227 │ put mut m .status_msg (str/append 'Exported 24-bit BMP -> ' bmp_path)
228 │ ]
229 │ .ok
230 │ ]
231 │
232 │ // Renders a complete `720x440` application frame into `c`.
233 │ pub render-frame = fn [
234 │ mut c cv/Canvas
235 │ mut ui_st w/UiState
236 │ mut m st/AppModel
237 │ db_path str
238 │ bmp_path str
239 │ ] [
240 │ th = if m.dark_mode [ w/dark-theme ] else [ w/light-theme ]
241 │ cv/clear mut c th.bg
242 │
243 │ root = w/Rect { x = 12, y = 10, w = (c.width - 24), h = (c.height - 20) }
244 │ rows = w/vstack root [38 322 36] 12
245 │ hdr = rows[0]
246 │ body = rows[1]
247 │ ftr = rows[2]
248 │
249 │ // Top header bar & navigation tabs
250 │ cv/fill-rounded-rect mut c hdr.x hdr.y hdr.w hdr.h 6 th.surface
251 │ cv/stroke-rect mut c hdr.x hdr.y hdr.w hdr.h 1 th.border
252 │ w/label mut c (hdr.x + 12) (hdr.y + 14) 'VEKO CANVAS WORKBENCH' 1 th.accent
253 │
254 │ tabs = ['1. TOPOLOGY' '2. SKETCH PAD' '3. SPRINT KV' '4. PROFILER']
255 │ mut ti = 0
256 │ while ti < 4 [
257 │ tr = w/Rect { x = (hdr.x + 172 + ti * 102), y = (hdr.y + 6), w = 96, h = 26 }
258 │ if w/button mut c mut ui_st (str/append 'tab-' (mold ti)) tr (str/append '' tabs[ti]) th [
259 │ put mut m .active_tab ti
260 │ put mut m .status_msg (str/append 'Switched view -> ' (str/append '' tabs[ti]))
261 │ ]
262 │ if m.active_tab == ti [
263 │ cv/fill-rect mut c (tr.x + 6) (tr.y + tr.h - 3) (tr.w - 12) 2 th.accent
264 │ ]
265 │ ti = ti + 1
266 │ ]
267 │
268 │ theme_lbl = if m.dark_mode [ 'THEME: DARK' ] else [ 'THEME: LIGHT' ]
269 │ if w/button mut c mut ui_st 'toggle-theme' (w/Rect { x = (hdr.x + hdr.w - 108), y = (hdr.y + 6), w = 98, h = 26 }) theme_lbl th [
270 │ put mut m .dark_mode (not m.dark_mode)
271 │ put mut m .status_msg (if m.dark_mode [ 'Switched to Dark Mode' ] else [ 'Switched to Light Mode' ])
272 │ ]
273 │
274 │ // Active single-view workspace body
275 │ if m.active_tab == 0 [ render-topology-tab mut c mut ui_st mut m body th ]
276 │ if m.active_tab == 1 [ render-paint-tab mut c mut ui_st mut m body th ]
277 │ if m.active_tab == 2 [ render-tasks-tab mut c mut ui_st mut m db_path body th ]
278 │ if m.active_tab == 3 [ render-bench-tab mut c mut ui_st mut m bmp_path body th ]
279 │
280 │ // Status bar footer
281 │ cv/fill-rounded-rect mut c ftr.x ftr.y ftr.w ftr.h 6 th.surface
282 │ cv/stroke-rect mut c ftr.x ftr.y ftr.w ftr.h 1 th.border
283 │ w/label mut c (ftr.x + 12) (ftr.y + 13) m.status_msg 1 th.muted
284 │ .ok
285 │ ]demos/canvas_workbench/src/main.vk
1 │ // demos/canvas_workbench/src/main.vk
2 │ // Canvas Workbench — Multi-module immediate-mode native desktop GUI application.
3 │ // - Default mode: deterministic cross-runtime verification across all 4 tabs, Light & Dark
4 │ // themes, `db/kv` task persistence, `.ui` window presentation, and 24-bit BMP export.
5 │ // - Live interactive OS window mode: pass `-- --live` (or compile with `--native --gui`).
6 │
7 │ use [
8 │ ui
9 │ cv = ui/canvas
10 │ png = image/png
11 │ w = ui/widgets
12 │ st = state
13 │ vw = views
14 │ ]
15 │
16 │ find-arg-val = fn [argv block, flag str] str [
17 │ mut i = 0
18 │ while i < (len argv) [
19 │ if (str/append '' argv[i]) == flag and (i + 1) < (len argv) [
20 │ return (str/append '' argv[i + 1])
21 │ ]
22 │ i = i + 1
23 │ ]
24 │ ''
25 │ ]
26 │
27 │ has-arg? = fn [argv block, flag str] bool [
28 │ mut i = 0
29 │ while i < (len argv) [
30 │ if argv[i] == flag [ return true ]
31 │ i = i + 1
32 │ ]
33 │ false
34 │ ]
35 │
36 │ run-live-loop = fn [win ui/Window, mut c cv/Canvas, mut ui_st w/UiState, mut m st/AppModel, db_path str, bmp_path str] [
37 │ mut running = true
38 │ mut mouse_down = false
39 │ mut mx = -1
40 │ mut my = -1
41 │ while running [
42 │ mut clicked = false
43 │ evs = ui/poll win
44 │ mut i = 0
45 │ while i < (len evs) [
46 │ ev = evs[i]
47 │ if ev.kind == (ui/EV-CLOSE) [ running = false ]
48 │ if ev.kind == (ui/EV-KEY) [
49 │ if ev.key == 27 [ running = false ]
50 │ if ev.key == 49 [ put mut m .active_tab 0 ]
51 │ if ev.key == 50 [ put mut m .active_tab 1 ]
52 │ if ev.key == 51 [ put mut m .active_tab 2 ]
53 │ if ev.key == 52 [ put mut m .active_tab 3 ]
54 │ if ev.key == 84 or ev.key == 116 [ put mut m .dark_mode (not m.dark_mode) ]
55 │ ]
56 │ if ev.kind == (ui/EV-MOUSE-MOVE) [
57 │ mx = ev.x
58 │ my = ev.y
59 │ ]
60 │ if ev.kind == (ui/EV-MOUSE-DOWN) [
61 │ mx = ev.x
62 │ my = ev.y
63 │ mouse_down = true
64 │ clicked = true
65 │ ]
66 │ if ev.kind == (ui/EV-MOUSE-UP) [
67 │ mx = ev.x
68 │ my = ev.y
69 │ mouse_down = false
70 │ ]
71 │ i = i + 1
72 │ ]
73 │ put mut m .pulse_tick (m.pulse_tick + 1)
74 │ w/apply-mouse mut ui_st mx my mouse_down clicked
75 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
76 │ _ = ui/present-canvas win c
77 │ time/sleep 16ms
78 │ ]
79 │ .ok
80 │ ]
81 │
82 │ main = fn [] any [
83 │ cw = 720
84 │ ch = 440
85 │ db_path = str/join [(os/temp-dir) '/veko_canvas_workbench.vkkv'] ''
86 │ bmp_path = str/join [(os/temp-dir) '/veko_canvas_workbench.bmp'] ''
87 │ _ = os/remove/or db_path [.ok]
88 │
89 │ mut c = cv/new-canvas cw ch
90 │ mut ui_st = w/new-state
91 │ mut m = st/AppModel {
92 │ tasks = st/load-persisted-tasks db_path
93 │ }
94 │
95 │ win = ui/open-window 'Veko 1.0 — Canvas Workbench' cw ch
96 │ argv = os/args
97 │ if (has-arg? argv '--live') and ((os/getenv/or 'VEKO_HEADLESS' ['']) != '1') [
98 │ run-live-loop win mut c mut ui_st mut m db_path bmp_path
99 │ _ = ui/close-window win
100 │ return .ok
101 │ ]
102 │
103 │ // Deterministic scripted UI tour across all 4 tabs & Light/Dark themes (runs on VM, Wasm & Native!)
104 │ // Frame 1: Light-theme Topology tab + click ADVANCE PULSE button
105 │ w/apply-mouse mut ui_st 60 398 true true
106 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
107 │ _ = ui/present-canvas win c
108 │ light_bg = cv/get-pixel c 4 4
109 │ png_out = find-arg-val argv '--export-png'
110 │ if png_out != '' [
111 │ _ = os/write-file/or png_out (png/encode c) [e -> return e]
112 │ ]
113 │
114 │ // Frame 2: Switch to Tab 2 (Sketch Pad) & paint a stroke
115 │ w/apply-mouse mut ui_st 320 28 true true
116 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
117 │ w/apply-mouse mut ui_st 220 180 true false
118 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
119 │
120 │ // Frame 3: Switch to Tab 3 (Durable Sprint Board) & mark a task done in db/kv
121 │ w/apply-mouse mut ui_st 422 28 true true
122 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
123 │ w/apply-mouse mut ui_st 560 144 true true
124 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
125 │
126 │ // Frame 4: Switch to Tab 4 (Crypto Profiler) & run SHA-256 rounds
127 │ w/apply-mouse mut ui_st 524 28 true true
128 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
129 │ w/apply-mouse mut ui_st 110 236 true true
130 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
131 │
132 │ // Export crisp Light-Mode 24-bit BMP snapshot
133 │ bmp_bytes = cv/encode-bmp c
134 │ if bmp_bytes[0] != 66 or bmp_bytes[1] != 77 [
135 │ return (err 'canvas_workbench: invalid BMP header')
136 │ ]
137 │
138 │ // Frame 5: Toggle Dark Mode via header button and verify theme switch
139 │ w/apply-mouse mut ui_st (cw - 60) 28 true true
140 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
141 │ w/apply-mouse mut ui_st -1 -1 false false
142 │ vw/render-frame mut c mut ui_st mut m db_path bmp_path
143 │ _ = ui/present-canvas win c
144 │ dark_bg = cv/get-pixel c 4 4
145 │
146 │ _ = ui/close-window win
147 │ _ = os/remove/or db_path [.ok]
148 │
149 │ if light_bg.r <= dark_bg.r [
150 │ return (err 'canvas_workbench: Light/Dark theme pixel contrast check failed')
151 │ ]
152 │ if m.sha_rounds != 80 or (len m.strokes) < 1 [
153 │ return (err 'canvas_workbench: scripted widget interaction invariant failed')
154 │ ]
155 │
156 │ println (str/join [
157 │ '[Canvas Workbench] canvas=' (mold cw) 'x' (mold ch)
158 │ ' tabs=4 themes=light+dark'
159 │ ' strokes=' (mold (len m.strokes))
160 │ ' tasks=' (mold (len m.tasks))
161 │ ' sha256-rounds=' (mold m.sha_rounds)
162 │ ' bmp=' (mold (len bmp_bytes)) 'B'
163 │ ] '')
164 │ .ok
165 │ ]
166 │
167 │ res = main
168 │ if err? res [
169 │ println (str/append 'FAIL: ' (mold res))
170 │ os/exit 1
171 │ ]Showcase 3: TaskFlow Studio — Full-Stack Web Portal & Durable Workflow Control Plane (demos/taskflow_studio/)
TaskFlow Studio is a multi-module, role-separated full-stack web application and workflow control plane written in 100% pure Veko (lib/web.vk, lib/durable/object.vk, lib/durable/workflow.vk, lib/db/kv.vk, lib/auth/jwt.vk, lib/auth/totp.vk, lib/crypto/kdf.vk).
Architecture & Modules
src/auth.vk:PBKDF2-SHA256password hashing,HS256JWT session tokens (HttpOnly; SameSite=Laxcookie +Authorization: Bearer), and RFC 6238 TOTP codes.src/store.vk: Crash-safe customer Durable Objects (dobj/mutate), replay-safeorder-fulfillmentDurable Workflows (wf/step,wf/wait-event,wf/send-event, LIFO sagarun-compensations), andAES-256-GCMsealed credentials (kv/put-sealed).src/ui_assets.vk: Self-contained Light-First Dual-Theme UI (data-theme="light"default + 1-click Dark Mode toggle), inline Eko vector SVG emblem, role-separated workspaces (/ui/auth,/ui/portal,/ui/admin), single-view sub-tabs, Lightbox modals,<select multiple>chip selector, and bottom-right toast stack.src/main.vk: Loopback E2E verification suite + liveweb/serve-reactorHTTP server (-- --serve [port]).
Running Across All Runtimes
veko check --strict-types demos/taskflow_studio/src/main.vk
veko run --allow-net --allow-listen --allow-private-net demos/taskflow_studio/src/main.vk
veko run --wasm --fuel=0 --allow-fs --allow-net --allow-listen --allow-private-net --check-slabs demos/taskflow_studio/src/main.vk
veko run --native demos/taskflow_studio/src/main.vk
veko run --native demos/taskflow_studio/src/main.vk -- --serve 8095Complete Module Listings
demos/taskflow_studio/veko.vk
{
name = 'taskflow_studio'
root = 'src'
allow-caps = [.fs .clocks .env .net]
}demos/taskflow_studio/src/auth.vk
1 │ // demos/taskflow_studio/src/auth.vk
2 │ // PBKDF2-SHA256 credential hashing, HS256 JWT bearer/cookie sessions, and RFC 6238 TOTP 2FA.
3 │
4 │ use [
5 │ jwt = auth/jwt
6 │ totp = auth/totp
7 │ kdf = crypto/kdf
8 │ hex = codec/hex
9 │ web
10 │ ]
11 │
12 │ pub Principal = struct {
13 │ sub str
14 │ role str
15 │ name str
16 │ valid bool
17 │ }
18 │
19 │ jwt-secret = fn [] bytes [
20 │ bytes/from-str 'veko-1.0-taskflow-studio-hmac-key-2026'
21 │ ]
22 │
23 │ pub hash-password = fn [password str, salt_tag str] str [
24 │ dk = kdf/pbkdf2-sha256 (bytes/from-str password) (bytes/from-str (str/append 'tf-salt:' salt_tag)) 64 32
25 │ hex/encode dk
26 │ ]
27 │
28 │ pub issue-session-token = fn [user_id str, role str, display_name str] str [
29 │ now_s = (time/unix) / 1000
30 │ jwt/sign-hs256 (jwt-secret) {
31 │ sub = user_id
32 │ role = role
33 │ name = display_name
34 │ iat = now_s
35 │ exp = (now_s + 86400)
36 │ }
37 │ ]
38 │
39 │ extract-cookie-token = fn [cookie_hdr str] str [
40 │ if cookie_hdr == '' [ return '' ]
41 │ parts = str/split cookie_hdr ';'
42 │ mut i = 0
43 │ while i < (len parts) [
44 │ seg = str/trim (str/append '' parts[i])
45 │ if str/contains? seg 'tf_session=' [
46 │ kvp = str/split seg '='
47 │ if (len kvp) >= 2 [ return (str/append '' kvp[1]) ]
48 │ ]
49 │ i = i + 1
50 │ ]
51 │ ''
52 │ ]
53 │
54 │ pub authenticate-request = fn [req web/Request] Principal [
55 │ auth_h = web/header req 'authorization' ''
56 │ mut tok = ''
57 │ if auth_h != '' [
58 │ pb = jwt/parse-bearer auth_h
59 │ if not (err? pb) [ tok = pb ]
60 │ ]
61 │ if tok == '' [
62 │ tok = extract-cookie-token (web/header req 'cookie' '')
63 │ ]
64 │ if tok == '' [
65 │ return (Principal { sub = '', role = '', name = '', valid = false })
66 │ ]
67 │ ver = jwt/verify-hs256 tok (jwt-secret)
68 │ if err? ver [
69 │ return (Principal { sub = '', role = '', name = '', valid = false })
70 │ ]
71 │ Principal {
72 │ sub = str/append '' (map/get/or ver.claims 'sub' [ '' ])
73 │ role = str/append '' (map/get/or ver.claims 'role' [ 'member' ])
74 │ name = str/append '' (map/get/or ver.claims 'name' [ '' ])
75 │ valid = true
76 │ }
77 │ ]
78 │
79 │ pub preview-totp-code = fn [user_id str] str [
80 │ seed = bytes/from-str (str/append 'totp-key-2026:' user_id)
81 │ totp/totp-at seed 1735689600 30 .sha1 6
82 │ ]demos/taskflow_studio/src/store.vk
1 │ // demos/taskflow_studio/src/store.vk
2 │ // Durable Objects (`customer` ledgers) + Durable Workflows (`order-fulfillment` with LIFO sagas)
3 │ // + AES-256-GCM sealed credentials over `db/kv`.
4 │
5 │ use [
6 │ d = durable
7 │ dobj = durable/object
8 │ wf = durable/workflow
9 │ kv = db/kv
10 │ auth
11 │ ]
12 │
13 │ seal-key = fn [] bytes [
14 │ bytes/from-str '0123456789abcdef0123456789abcdef'
15 │ ]
16 │
17 │ // Seeds demo accounts (`cust-alice`, `cust-bob`, `admin-ops`) and a sealed webhook credential.
18 │ pub init-seed-data = fn [store_path str] [
19 │ mut db = d/open-store-fast store_path
20 │ mut alice = d/object mut db 'customer' 'cust-alice'
21 │ _ = dobj/put-fields mut db mut alice {
22 │ name = 'Alice Chen'
23 │ role = 'member'
24 │ balance = 1000
25 │ pass_hash = (auth/hash-password 'alice-pass' 'cust-alice')
26 │ }
27 │ mut bob = d/object mut db 'customer' 'cust-bob'
28 │ _ = dobj/put-fields mut db mut bob {
29 │ name = 'Bob Rivera'
30 │ role = 'member'
31 │ balance = 50
32 │ pass_hash = (auth/hash-password 'bob-pass' 'cust-bob')
33 │ }
34 │ mut adm = d/object mut db 'customer' 'admin-ops'
35 │ _ = dobj/put-fields mut db mut adm {
36 │ name = 'Jordan Ops'
37 │ role = 'admin'
38 │ balance = 5000
39 │ pass_hash = (auth/hash-password 'admin-pass' 'admin-ops')
40 │ }
41 │ _ = kv/put-sealed mut db 'secret:carrier-api-key' (seal-key) (bytes/from-str 'ship_live_veko_994411')
42 │ _ = d/close-store mut db
43 │ .ok
44 │ ]
45 │
46 │ // Executes or replays a crash-safe order fulfillment workflow against `store_path`.
47 │ pub execute-order-pass = fn [store_path str, order_id str, cust_id str, amount i64, tags block] any [
48 │ mut db = d/open-store-fast store_path
49 │ mut run = d/workflow mut db order_id 'order-fulfillment' {
50 │ customer = cust_id
51 │ amount = amount
52 │ tags = tags
53 │ }
54 │
55 │ // Step 1: Memoized inventory reservation
56 │ res_id = wf/step mut db mut run 'reserve-stock' fn [] [
57 │ str/append 'inv-' order_id
58 │ ]
59 │ if err? res_id [
60 │ _ = d/close-store mut db
61 │ return res_id
62 │ ]
63 │
64 │ // Step 2: Atomic Durable Object debit guarded by workflow step checkpoint (never double-charges!)
65 │ charge_res = if wf/step-done? db run 'charge-customer' [
66 │ wf/step-result db run 'charge-customer'
67 │ ] else [
68 │ mut acct = d/object mut db 'customer' cust_id
69 │ deb = dobj/mutate mut db mut acct fn [st] [
70 │ bal = as-i64 (map/get/or st 'balance' [ 0 ])
71 │ if bal < amount [ return (err 'insufficient balance') ]
72 │ mut next = st
73 │ map/set mut next 'balance' (bal - amount)
74 │ { state = next, result = (bal - amount) }
75 │ ]
76 │ if err? deb [
77 │ deb
78 │ ] else [
79 │ wf/step mut db mut run 'charge-customer' fn [] [ deb ]
80 │ ]
81 │ ]
82 │ if err? charge_res [
83 │ _ = wf/record-compensation mut db mut run 'release-stock' res_id
84 │ _ = wf/run-compensations mut db mut run fn [cname data] [ .ok ]
85 │ _ = wf/fail mut db mut run 'insufficient balance (LIFO saga compensated)'
86 │ _ = d/close-store mut db
87 │ return charge_res
88 │ ]
89 │
90 │ // Step 3: Suspend cleanly until warehouse packing webhook signal arrives
91 │ packed = wf/wait-event mut db mut run 'warehouse-packed'
92 │ if not packed.ready [
93 │ _ = d/close-store mut db
94 │ return .waiting
95 │ ]
96 │
97 │ // Step 4: Issue carrier tracking number & mark workflow complete
98 │ tracking = wf/step mut db mut run 'dispatch' fn [] [
99 │ str/join ['TRK-' order_id '-' (str/append '' packed.payload)] ''
100 │ ]
101 │ if err? tracking [
102 │ _ = d/close-store mut db
103 │ return tracking
104 │ ]
105 │ _ = wf/complete mut db mut run {
106 │ reservation = res_id
107 │ remaining_balance = charge_res
108 │ tracking = tracking
109 │ }
110 │ _ = d/close-store mut db
111 │ .completed
112 │ ]
113 │
114 │ pub deliver-packing-signal = fn [store_path str, order_id str, box_code str] any [
115 │ mut db = d/open-store-fast store_path
116 │ meta = wf/get-status db order_id
117 │ inp = map/get/or meta 'input' [ {} ]
118 │ cust_id = str/append '' (map/get/or inp 'customer' [ 'cust-alice' ])
119 │ amount = as-i64 (map/get/or inp 'amount' [ 0 ])
120 │ _ = wf/send-event mut db order_id 'warehouse-packed' box_code
121 │ _ = d/close-store mut db
122 │ execute-order-pass store_path order_id cust_id amount []
123 │ ]
124 │
125 │ pub verify-login = fn [store_path str, user_id str, password str] map [
126 │ mut db = d/open-store-fast store_path
127 │ ref = dobj/ObjectRef { ns = 'customer', id = user_id }
128 │ st = dobj/state db ref
129 │ _ = d/close-store mut db
130 │ expected = str/append '' (map/get/or st 'pass_hash' [ '' ])
131 │ if expected == '' [ return { ok = false, role = '', name = '' } ]
132 │ got = auth/hash-password password user_id
133 │ if got != expected [ return { ok = false, role = '', name = '' } ]
134 │ {
135 │ ok = true
136 │ role = str/append '' (map/get/or st 'role' [ 'member' ])
137 │ name = str/append '' (map/get/or st 'name' [ user_id ])
138 │ }
139 │ ]
140 │
141 │ pub read-self-summary = fn [store_path str, user_id str] map [
142 │ mut db = d/open-store-fast store_path
143 │ ref = dobj/ObjectRef { ns = 'customer', id = user_id }
144 │ st = dobj/state db ref
145 │ runs = wf/list-runs db
146 │ mut my_orders = []
147 │ mut i = 0
148 │ while i < (len runs) [
149 │ rid = str/append '' runs[i]
150 │ meta = wf/get-status db rid
151 │ inp = map/get/or meta 'input' [ {} ]
152 │ if (str/append '' (map/get/or inp 'customer' [ '' ])) == user_id [
153 │ push mut my_orders {
154 │ id = rid
155 │ status = str/append '' (map/get/or meta 'status' [ 'unknown' ])
156 │ amount = as-i64 (map/get/or inp 'amount' [ 0 ])
157 │ steps = as-i64 (map/get/or meta 'step_count' [ 0 ])
158 │ }
159 │ ]
160 │ i = i + 1
161 │ ]
162 │ sealed_len = as-i64 (kv/with-open-sealed db 'secret:carrier-api-key' (seal-key) fn [pt bytes] i64 [ len pt ])
163 │ _ = d/close-store mut db
164 │ {
165 │ user_id = user_id
166 │ name = str/append '' (map/get/or st 'name' [ user_id ])
167 │ role = str/append '' (map/get/or st 'role' [ 'member' ])
168 │ balance = as-i64 (map/get/or st 'balance' [ 0 ])
169 │ orders = my_orders
170 │ totp_demo = auth/preview-totp-code user_id
171 │ sealed_len = sealed_len
172 │ }
173 │ ]
174 │
175 │ pub read-admin-overview = fn [store_path str] map [
176 │ mut db = d/open-store-fast store_path
177 │ accts = dobj/list-ids db 'customer'
178 │ mut customers = []
179 │ mut i = 0
180 │ while i < (len accts) [
181 │ aid = str/append '' accts[i]
182 │ st = dobj/state db (dobj/ObjectRef { ns = 'customer', id = aid })
183 │ push mut customers {
184 │ id = aid
185 │ name = str/append '' (map/get/or st 'name' [ aid ])
186 │ role = str/append '' (map/get/or st 'role' [ 'member' ])
187 │ balance = as-i64 (map/get/or st 'balance' [ 0 ])
188 │ }
189 │ i = i + 1
190 │ ]
191 │ runs = wf/list-runs db
192 │ mut workflows = []
193 │ mut j = 0
194 │ while j < (len runs) [
195 │ rid = str/append '' runs[j]
196 │ meta = wf/get-status db rid
197 │ push mut workflows {
198 │ id = rid
199 │ status = str/append '' (map/get/or meta 'status' [ 'unknown' ])
200 │ step_count = as-i64 (map/get/or meta 'step_count' [ 0 ])
201 │ meta = meta
202 │ }
203 │ j = j + 1
204 │ ]
205 │ _ = d/close-store mut db
206 │ {
207 │ customers = customers
208 │ workflows = workflows
209 │ }
210 │ ]demos/taskflow_studio/src/ui_assets.vk
1 │ // demos/taskflow_studio/src/ui_assets.vk
2 │ // Self-contained Light-First Dual-Theme UI shells (`/ui/auth`, `/ui/portal`, `/ui/admin`)
3 │ // with inline Eko Galago vector SVG emblem, single-view sub-tabs, Lightbox modal,
4 │ // `<select multiple>` chip selector, and non-blocking toast notifications.
5 │
6 │ eko-emblem-svg = fn [px i64] str [
7 │ sz = mold px
8 │ str/join [
9 │ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="' sz '" height="' sz '" role="img" aria-label="Veko TaskFlow Studio">'
10 │ '<defs><linearGradient id="tf-fur" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#a8a29e"/><stop offset="100%" stop-color="#57534e"/></linearGradient>'
11 │ '<linearGradient id="tf-iris" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#fbbf24"/><stop offset="100%" stop-color="#b45309"/></linearGradient></defs>'
12 │ '<path d="M 37 56 C 14 44, 11 17, 26 13 C 40 9, 52 28, 54 46 Z" fill="url(#tf-fur)"/>'
13 │ '<path d="M 91 56 C 114 44, 117 17, 102 13 C 88 9, 76 28, 74 46 Z" fill="url(#tf-fur)"/>'
14 │ '<ellipse cx="64" cy="74" rx="40" ry="36" fill="url(#tf-fur)"/>'
15 │ '<ellipse cx="64" cy="85" rx="25" ry="21" fill="#fafaf9"/>'
16 │ '<path d="M 64 45 L 59 74 L 69 74 Z" fill="#fafaf9"/>'
17 │ '<circle cx="46" cy="70" r="16" fill="#292524"/><circle cx="82" cy="70" r="16" fill="#292524"/>'
18 │ '<circle cx="46" cy="70" r="13" fill="url(#tf-iris)"/><circle cx="82" cy="70" r="13" fill="url(#tf-iris)"/>'
19 │ '<circle cx="46" cy="70" r="8" fill="#0c0a09"/><circle cx="82" cy="70" r="8" fill="#0c0a09"/>'
20 │ '<circle cx="42.5" cy="65.5" r="3.5" fill="#ffffff"/><circle cx="78.5" cy="65.5" r="3.5" fill="#ffffff"/>'
21 │ '<polygon points="60,83 68,83 64,88" fill="#fb7185"/>'
22 │ '<path d="M 58 92 Q 64 96 70 92" fill="none" stroke="#44403c" stroke-width="2.5" stroke-linecap="round"/></svg>'
23 │ ] ''
24 │ ]
25 │
26 │ shared-css = fn [] str [
27 │ ':root, [data-theme="light"] {
28 │ --bg-canvas: #f8fafc; --bg-surface: #ffffff; --bg-elevated: #ffffff; --bg-overlay: #f1f5f9;
29 │ --text-primary: #0f172a; --text-secondary: #334155; --text-muted: #64748b;
30 │ --accent-primary: #2563eb; --accent-secondary: #0284c7; --border-subtle: #cbd5e1;
31 │ --shadow-card: 0 2px 8px rgba(15, 23, 42, 0.05);
32 │ }
33 │ [data-theme="dark"] {
34 │ --bg-canvas: #0b1120; --bg-surface: #0f172a; --bg-elevated: #1e293b; --bg-overlay: #1e293b;
35 │ --text-primary: #f8fafc; --text-secondary: #cbd5e1; --text-muted: #94a3b8;
36 │ --accent-primary: #3b82f6; --accent-secondary: #38bdf8; --border-subtle: #334155;
37 │ --shadow-card: 0 4px 16px rgba(0, 0, 0, 0.35);
38 │ }
39 │ * { box-sizing: border-box; }
40 │ body { margin: 0; background: var(--bg-canvas); color: var(--text-primary); font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.55; }
41 │ code, pre, .mono { font-family: "Cascadia Mono", "JetBrains Mono", Consolas, monospace; }
42 │ .topbar { display: flex; align-items: center; justify-content: space-between; padding: 14px 28px; background: var(--bg-surface); border-bottom: 1px solid var(--border-subtle); }
43 │ .brand { display: flex; align-items: center; gap: 14px; }
44 │ .brand-title { font-size: 1.15rem; font-weight: 800; }
45 │ .brand-sub { font-size: 0.8rem; color: var(--text-muted); }
46 │ .container { max-width: 1120px; margin: 24px auto; padding: 0 20px; }
47 │ .subtabs { display: flex; gap: 8px; border-bottom: 1px solid var(--border-subtle); padding-bottom: 12px; margin-bottom: 20px; flex-wrap: wrap; }
48 │ .tab-btn, .btn { padding: 8px 14px; border-radius: 7px; border: 1px solid var(--border-subtle); background: var(--bg-surface); color: var(--text-primary); font-weight: 600; font-size: 0.86rem; cursor: pointer; }
49 │ .tab-btn.active, .btn-primary { background: var(--accent-primary); color: #ffffff; border-color: var(--accent-primary); }
50 │ .card { background: var(--bg-surface); border: 1px solid var(--border-subtle); border-radius: 10px; padding: 22px; box-shadow: var(--shadow-card); margin-bottom: 18px; }
51 │ .grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; }
52 │ table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
53 │ th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--border-subtle); }
54 │ th { color: var(--text-muted); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.05em; }
55 │ .input-ctrl, .select-ctrl { width: 100%; padding: 8px 11px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-canvas); color: var(--text-primary); margin-top: 4px; margin-bottom: 12px; }
56 │ .chip-row { display: flex; gap: 6px; flex-wrap: wrap; margin: 6px 0; }
57 │ .chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; border-radius: 5px; background: var(--bg-overlay); border: 1px solid var(--border-subtle); font-size: 0.78rem; }
58 │ .view-pane { display: none; }
59 │ .view-pane.active { display: block; }
60 │ #lightbox-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55); display: none; align-items: center; justify-content: center; z-index: 100; padding: 20px; }
61 │ #lightbox-backdrop.open { display: flex; }
62 │ .modal-card { background: var(--bg-surface); border: 1px solid var(--border-subtle); border-radius: 12px; padding: 24px; width: min(560px, 100%); max-height: 85vh; overflow: auto; }
63 │ #toast-stack { position: fixed; right: 20px; bottom: 20px; display: flex; flex-direction: column; gap: 8px; z-index: 200; }
64 │ .toast { background: var(--bg-elevated); color: var(--text-primary); border: 1px solid var(--accent-primary); border-left-width: 4px; padding: 10px 14px; border-radius: 8px; box-shadow: var(--shadow-card); font-size: 0.85rem; }
65 │ .auth-wrap { max-width: 430px; margin: 48px auto; text-align: center; padding: 0 16px; }'
66 │ ]
67 │
68 │ shared-theme-toast-js = fn [] str [
69 │ 'function initTheme(){var t=localStorage.getItem("tf_theme")||"light";document.documentElement.setAttribute("data-theme",t);}
70 │ function toggleTheme(){var c=document.documentElement.getAttribute("data-theme")||"light";var n=c==="light"?"dark":"light";document.documentElement.setAttribute("data-theme",n);localStorage.setItem("tf_theme",n);}
71 │ function showToast(msg){var s=document.getElementById("toast-stack");if(!s)return;var d=document.createElement("div");d.className="toast";d.textContent=msg;s.appendChild(d);setTimeout(function(){d.remove();},4000);}
72 │ function openModal(html){var b=document.getElementById("lightbox-backdrop");document.getElementById("modal-body").innerHTML=html;b.classList.add("open");}
73 │ function closeModal(){document.getElementById("lightbox-backdrop").classList.remove("open");}
74 │ document.addEventListener("keydown",function(e){if(e.key==="Escape")closeModal();});
75 │ function switchTab(id,btn){document.querySelectorAll(".view-pane").forEach(function(p){p.classList.remove("active");});document.querySelectorAll(".tab-btn").forEach(function(b){b.classList.remove("active");});document.getElementById(id).classList.add("active");btn.classList.add("active");}
76 │ initTheme();'
77 │ ]
78 │
79 │ pub render-auth-page = fn [] str [
80 │ str/join [
81 │ '<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="utf-8"/><title>Sign In — TaskFlow Studio</title><style>'
82 │ (shared-css)
83 │ '</style></head><body><div class="auth-wrap">'
84 │ (eko-emblem-svg 104)
85 │ '<div class="card" style="text-align:left;margin-top:16px;"><h2 style="margin-top:0;">TaskFlow Studio Sign In</h2>'
86 │ '<p style="color:var(--text-muted);font-size:0.88rem;">Durable Objects & Replay-Safe Workflows powered by Veko 1.0</p>'
87 │ '<label>Account ID</label><input id="uid" class="input-ctrl" value="cust-alice" />'
88 │ '<label>Password</label><input id="pwd" type="password" class="input-ctrl" value="alice-pass" />'
89 │ '<div style="display:flex;gap:8px;"><button class="btn btn-primary" onclick="doLogin()">Sign In</button>'
90 │ '<button class="btn" onclick="toggleTheme()">Light / Dark</button></div>'
91 │ '<p style="font-size:0.78rem;color:var(--text-muted);margin-top:14px;">Demo accounts: <code>cust-alice / alice-pass</code> (Portal) or <code>admin-ops / admin-pass</code> (Admin Console)</p>'
92 │ '</div></div><div id="toast-stack"></div><script>'
93 │ (shared-theme-toast-js)
94 │ 'async function doLogin(){var u=document.getElementById("uid").value,p=document.getElementById("pwd").value;'
95 │ 'var r=await fetch("/api/v1/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user_id:u,password:p})});'
96 │ 'var d=await r.json();if(!r.ok){showToast(d.error||"Sign-in failed");return;}'
97 │ 'localStorage.setItem("tf_token",d.token);window.location.href=(d.role==="admin")?"/ui/admin":"/ui/portal";}'
98 │ '</script></body></html>'
99 │ ] ''
100 │ ]
101 │
102 │ pub render-portal-page = fn [] str [
103 │ str/join [
104 │ '<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="utf-8"/><title>Member Portal — TaskFlow Studio</title><style>'
105 │ (shared-css)
106 │ '</style></head><body><header class="topbar"><div class="brand">'
107 │ (eko-emblem-svg 76)
108 │ '<div><div class="brand-title">TaskFlow Member Portal</div><div class="brand-sub">Self-Service Orders, Durable Wallet & Sealed Keys</div></div></div>'
109 │ '<div style="display:flex;gap:8px;"><button class="btn btn-primary" onclick="openNewOrderModal()">+ New Order</button>'
110 │ '<button class="btn" onclick="toggleTheme()">Theme</button><a class="btn" href="/ui/auth">Sign Out</a></div></header>'
111 │ '<main class="container"><div class="subtabs">'
112 │ '<button class="tab-btn active" onclick="switchTab(\'pane-orders\',this)">My Orders & Workflows</button>'
113 │ '<button class="tab-btn" onclick="switchTab(\'pane-wallet\',this)">Wallet Durable Object</button>'
114 │ '<button class="tab-btn" onclick="switchTab(\'pane-keys\',this)">Sealed Credentials</button>'
115 │ '<button class="tab-btn" onclick="switchTab(\'pane-totp\',this)">Security & TOTP</button></div>'
116 │ '<section id="pane-orders" class="view-pane active"><div class="card"><h3>My Durable Fulfillment Runs</h3><table><thead><tr><th>Order ID</th><th>Amount</th><th>State</th><th>Checkpoints</th></tr></thead><tbody id="orders-tbody"></tbody></table></div></section>'
117 │ '<section id="pane-wallet" class="view-pane"><div class="card"><h3>Strongly Consistent Wallet Balance</h3><p id="wallet-balance" class="mono" style="font-size:1.8rem;font-weight:800;">$0</p><p style="color:var(--text-muted);">Guarded by workflow step checkpoints so crash replays never double-debit your account.</p></div></section>'
118 │ '<section id="pane-keys" class="view-pane"><div class="card"><h3>AES-256-GCM Sealed Carrier Key</h3><p id="sealed-info" class="mono"></p></div></section>'
119 │ '<section id="pane-totp" class="view-pane"><div class="card"><h3>RFC 6238 TOTP Verification</h3><p>Current reference TOTP code: <code id="totp-code"></code></p></div></section></main>'
120 │ '<div id="lightbox-backdrop" onclick="if(event.target===this)closeModal()"><div class="modal-card" id="modal-body"></div></div>'
121 │ '<div id="toast-stack"></div><script>'
122 │ (shared-theme-toast-js)
123 │ 'var selectedTags=["priority"];'
124 │ 'async function loadSelf(){var tok=localStorage.getItem("tf_token")||"";var r=await fetch("/api/v1/self/summary",{headers:tok?{"Authorization":"Bearer "+tok}:{}});'
125 │ 'if(r.status===401){window.location.href="/ui/auth";return;}var d=await r.json();'
126 │ 'document.getElementById("wallet-balance").textContent="$"+d.balance;'
127 │ 'document.getElementById("sealed-info").textContent="secret:carrier-api-key ("+d.sealed_len+" bytes sealed in db/kv)";'
128 │ 'document.getElementById("totp-code").textContent=d.totp_demo;'
129 │ 'var tb=document.getElementById("orders-tbody");tb.innerHTML="";(d.orders||[]).forEach(function(o){var tr=document.createElement("tr");tr.innerHTML="<td class=mono>"+o.id+"</td><td>$"+o.amount+"</td><td>"+o.status+"</td><td>"+o.steps+"</td>";tb.appendChild(tr);});}'
130 │ 'function openNewOrderModal(){openModal("<h3>Create Durable Order</h3><label>Order ID</label><input id=m-oid class=input-ctrl value=ord-"+Math.floor(1000+Math.random()*9000)+" /><label>Amount (USD)</label><input id=m-amt type=number class=input-ctrl value=120 /><label>Fulfillment Tags</label><div id=chip-box class=chip-row></div><select id=m-tags multiple size=4 class=\'select-ctrl multi-select-box\' onclick=\'syncChips()\'><option value=priority selected>priority</option><option value=fragile>fragile</option><option value=insured>insured</option><option value=cold-chain>cold-chain</option></select><div style=\'display:flex;gap:8px;margin-top:8px;\'><input id=m-custom class=input-ctrl placeholder=\'Custom tag\' style=\'margin:0;\'/><button class=btn onclick=\'addCustomTag()\'>+ Add</button></div><div style=\'display:flex;gap:8px;justify-content:flex-end;margin-top:16px;\'><button class=btn onclick=closeModal()>Cancel</button><button class=\'btn btn-primary\' onclick=submitOrder()>Submit Order</button></div>");syncChips();}'
131 │ 'function syncChips(){var sel=document.getElementById("m-tags");if(!sel)return;var box=document.getElementById("chip-box");box.innerHTML="";Array.from(sel.selectedOptions).forEach(function(opt){var s=document.createElement("span");s.className="chip";s.textContent=opt.value;box.appendChild(s);});}'
132 │ 'function addCustomTag(){var inp=document.getElementById("m-custom"),sel=document.getElementById("m-tags");if(inp.value.trim()){var o=new Option(inp.value.trim(),inp.value.trim(),true,true);sel.add(o);inp.value="";syncChips();}}'
133 │ 'async function submitOrder(){var tok=localStorage.getItem("tf_token")||"";var tags=Array.from(document.getElementById("m-tags").selectedOptions).map(function(o){return o.value;});'
134 │ 'var r=await fetch("/api/v1/self/orders",{method:"POST",headers:{"Content-Type":"application/json","Authorization":"Bearer "+tok},body:JSON.stringify({order_id:document.getElementById("m-oid").value,amount:parseInt(document.getElementById("m-amt").value,10),tags:tags})});'
135 │ 'var d=await r.json();closeModal();showToast(d.message||d.error||"Updated");loadSelf();}'
136 │ 'loadSelf();</script></body></html>'
137 │ ] ''
138 │ ]
139 │
140 │ pub render-admin-page = fn [] str [
141 │ str/join [
142 │ '<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="utf-8"/><title>Admin Console — TaskFlow Studio</title><style>'
143 │ (shared-css)
144 │ '</style></head><body><header class="topbar"><div class="brand">'
145 │ (eko-emblem-svg 76)
146 │ '<div><div class="brand-title">TaskFlow Operations Console</div><div class="brand-sub">Global Workflow Orchestrator, Webhook Signals & Customer Ledgers</div></div></div>'
147 │ '<div style="display:flex;gap:8px;"><button class="btn" onclick="toggleTheme()">Theme</button><a class="btn" href="/ui/auth">Sign Out</a></div></header>'
148 │ '<main class="container"><div class="subtabs">'
149 │ '<button class="tab-btn active" onclick="switchTab(\'adm-wf\',this)">Workflow Orchestrator</button>'
150 │ '<button class="tab-btn" onclick="switchTab(\'adm-cust\',this)">Customer Durable Ledgers</button>'
151 │ '<button class="tab-btn" onclick="switchTab(\'adm-wal\',this)">WAL & Reactor Telemetry</button></div>'
152 │ '<section id="adm-wf" class="view-pane active"><div class="card"><h3>All Workflow Runs</h3><table><thead><tr><th>Run ID</th><th>State</th><th>Steps</th><th>Actions</th></tr></thead><tbody id="wf-tbody"></tbody></table></div></section>'
153 │ '<section id="adm-cust" class="view-pane"><div class="card"><h3>Customer Durable Objects</h3><table><thead><tr><th>ID</th><th>Name</th><th>Role</th><th>Balance</th></tr></thead><tbody id="cust-tbody"></tbody></table></div></section>'
154 │ '<section id="adm-wal" class="view-pane"><div class="card"><h3>Embedded db/kv & Readiness Reactor</h3><p>Engine: CRC-32 Append-Only WAL + Non-Blocking <code>web/serve-reactor</code></p></div></section></main>'
155 │ '<div id="lightbox-backdrop" onclick="if(event.target===this)closeModal()"><div class="modal-card" id="modal-body"></div></div>'
156 │ '<div id="toast-stack"></div><script>'
157 │ (shared-theme-toast-js)
158 │ 'var wfCache={};'
159 │ 'async function loadAdmin(){var tok=localStorage.getItem("tf_token")||"";var r=await fetch("/api/v1/admin/overview",{headers:tok?{"Authorization":"Bearer "+tok}:{}});'
160 │ 'if(r.status===401||r.status===403){window.location.href="/ui/auth";return;}var d=await r.json();'
161 │ 'var wt=document.getElementById("wf-tbody");wt.innerHTML="";(d.workflows||[]).forEach(function(w){wfCache[w.id]=w;var tr=document.createElement("tr");'
162 │ 'tr.innerHTML="<td class=mono>"+w.id+"</td><td>"+w.status+"</td><td>"+w.step_count+"</td><td><button class=btn onclick=\\"signalPack(\'"+w.id+"\')\\">Send Packed Signal</button> <button class=btn onclick=\\"inspectWf(\'"+w.id+"\')\\">Inspect JSON</button></td>";wt.appendChild(tr);});'
163 │ 'var ct=document.getElementById("cust-tbody");ct.innerHTML="";(d.customers||[]).forEach(function(c){var tr=document.createElement("tr");tr.innerHTML="<td class=mono>"+c.id+"</td><td>"+c.name+"</td><td>"+c.role+"</td><td>$"+c.balance+"</td>";ct.appendChild(tr);});}'
164 │ 'function inspectWf(id){openModal("<h3>Workflow Checkpoint Metadata</h3><pre style=\'background:var(--bg-overlay);padding:12px;border-radius:8px;overflow:auto;\'>"+JSON.stringify(wfCache[id],null,2)+"</pre><div style=\'text-align:right;margin-top:12px;\'><button class=btn onclick=closeModal()>Close</button></div>");}'
165 │ 'async function signalPack(id){var tok=localStorage.getItem("tf_token")||"";var r=await fetch("/api/v1/admin/signal",{method:"POST",headers:{"Content-Type":"application/json","Authorization":"Bearer "+tok},body:JSON.stringify({order_id:id,box_code:"BOX-900"})});'
166 │ 'var d=await r.json();showToast(d.message||"Signal delivered");loadAdmin();}'
167 │ 'loadAdmin();</script></body></html>'
168 │ ] ''
169 │ ]demos/taskflow_studio/src/main.vk
1 │ // demos/taskflow_studio/src/main.vk
2 │ // TaskFlow Studio — Multi-View Role-Separated Web Application & Durable Workflow Control Plane.
3 │ // - Default mode: runs an end-to-end client-server verification over loopback HTTP (`web/serve-async`
4 │ // + `net/client`) testing JWT auth, role gating, Durable Object debits, crash/replay idempotency,
5 │ // webhook signals, LIFO saga overdraft rollbacks, and Light-First UI workspaces.
6 │ // - Live server mode: pass `-- --serve [port]` to serve the persistent web studio via `web/serve-reactor`.
7 │
8 │ use [
9 │ web
10 │ nc = net/client
11 │ inet = io/net
12 │ auth
13 │ st = store
14 │ ui = ui_assets
15 │ ]
16 │
17 │ pub make-studio-app = fn [store_path str] web/App [
18 │ mut app = web/new-app
19 │
20 │ web/get mut app '/' fn [req web/Request] web/Response [
21 │ web/redirect 302 '/ui/auth'
22 │ ]
23 │ web/get mut app '/ui/auth' fn [req web/Request] web/Response [
24 │ web/html 200 (ui/render-auth-page)
25 │ ]
26 │ web/get mut app '/ui/portal' fn [req web/Request] web/Response [
27 │ web/html 200 (ui/render-portal-page)
28 │ ]
29 │ web/get mut app '/ui/admin' fn [req web/Request] web/Response [
30 │ web/html 200 (ui/render-admin-page)
31 │ ]
32 │
33 │ web/post mut app '/api/v1/auth/login' fn [req web/Request] web/Response [
34 │ b_raw = web/bind-json req
35 │ body = if err? b_raw [ {} ] else [ b_raw ]
36 │ uid = str/append '' (map/get/or body 'user_id' [ '' ])
37 │ pwd = str/append '' (map/get/or body 'password' [ '' ])
38 │ ver = st/verify-login store_path uid pwd
39 │ if not ver.ok [
40 │ return (web/json-resp 401 { error = 'Invalid credentials' })
41 │ ]
42 │ rl = str/append '' ver.role
43 │ nm = str/append '' ver.name
44 │ tok = auth/issue-session-token uid rl nm
45 │ mut resp = web/json-resp 200 { ok = true, token = tok, role = rl, name = nm }
46 │ mut hdrs = resp.headers
47 │ map/set mut hdrs 'Set-Cookie' (str/join ['tf_session=' tok '; Path=/; HttpOnly; SameSite=Lax'] '')
48 │ put mut resp .headers hdrs
49 │ resp
50 │ ]
51 │
52 │ web/get mut app '/api/v1/self/summary' fn [req web/Request] web/Response [
53 │ p = auth/authenticate-request req
54 │ if not p.valid [ return (web/json-resp 401 { error = 'Unauthorized' }) ]
55 │ web/json-resp 200 (st/read-self-summary store_path p.sub)
56 │ ]
57 │
58 │ web/post mut app '/api/v1/self/orders' fn [req web/Request] web/Response [
59 │ p = auth/authenticate-request req
60 │ if not p.valid [ return (web/json-resp 401 { error = 'Unauthorized' }) ]
61 │ b_raw = web/bind-json req
62 │ body = if err? b_raw [ {} ] else [ b_raw ]
63 │ oid = str/append '' (map/get/or body 'order_id' [ 'ord-auto' ])
64 │ amt = as-i64 (map/get/or body 'amount' [ 100 ])
65 │ tags_raw = map/get/or body 'tags' [ [] ]
66 │ tags = if (type-of tags_raw) == .block [ tags_raw ] else [ [] ]
67 │ outcome = st/execute-order-pass store_path oid p.sub amt tags
68 │ if err? outcome [
69 │ return (web/json-resp 422 { ok = false, error = 'Insufficient balance — LIFO saga compensated' })
70 │ ]
71 │ web/json-resp 201 { ok = true, order_id = oid, state = (mold outcome), message = (str/append 'Order parked on warehouse signal: ' oid) }
72 │ ]
73 │
74 │ web/get mut app '/api/v1/admin/overview' fn [req web/Request] web/Response [
75 │ p = auth/authenticate-request req
76 │ if not p.valid [ return (web/json-resp 401 { error = 'Unauthorized' }) ]
77 │ if p.role != 'admin' [ return (web/json-resp 403 { error = 'Admin role required' }) ]
78 │ web/json-resp 200 (st/read-admin-overview store_path)
79 │ ]
80 │
81 │ web/post mut app '/api/v1/admin/signal' fn [req web/Request] web/Response [
82 │ p = auth/authenticate-request req
83 │ if (not p.valid) or p.role != 'admin' [ return (web/json-resp 403 { error = 'Admin role required' }) ]
84 │ b_raw = web/bind-json req
85 │ body = if err? b_raw [ {} ] else [ b_raw ]
86 │ oid = str/append '' (map/get/or body 'order_id' [ '' ])
87 │ box = str/append '' (map/get/or body 'box_code' [ 'BOX-42' ])
88 │ res = st/deliver-packing-signal store_path oid box
89 │ if err? res [ return (web/json-resp 500 { error = (mold res) }) ]
90 │ web/json-resp 200 { ok = true, state = (mold res), message = (str/append 'Completed workflow ' oid) }
91 │ ]
92 │
93 │ app
94 │ ]
95 │
96 │ run-e2e-verification = fn [store_path str] any [
97 │ _ = os/remove/or store_path [.ok]
98 │ st/init-seed-data store_path
99 │
100 │ // Bob's $300 order triggers overdraft rollback + LIFO saga compensation ($50 untouched)
101 │ s_bob = st/execute-order-pass store_path 'ord-1002' 'cust-bob' 300 ['fragile']
102 │ if not (err? s_bob) [ return (err 'taskflow: expected ord-1002 overdraft rollback') ]
103 │
104 │ // Boot loopback web server for 6 HTTP API & UI verification requests
105 │ ln = net/listen-tcp .ip '127.0.0.1:0'
106 │ base = str/append 'http://' (net/addr ln)
107 │ srv = spawn [
108 │ n = web/serve-async ln (make-studio-app store_path) 6
109 │ _ = net/close ln
110 │ n
111 │ ]
112 │ time/sleep 20ms
113 │
114 │ // 1. Sign in as Alice (member)
115 │ def_opts = nc/RequestOpts { timeout = 15s }
116 │ r_alice = nc/post-json (str/append base '/api/v1/auth/login') { user_id = 'cust-alice', password = 'alice-pass' } def_opts
117 │ d_alice = json/decode (bytes/to-str r_alice.body)
118 │ alice_tok = str/append '' (map/get d_alice 'token')
119 │
120 │ // 2. Submit $240 order via member API (parks in .waiting)
121 │ r_ord = nc/request 'POST' (str/append base '/api/v1/self/orders') (bytes/from-str (json/encode { order_id = 'ord-1001', amount = 240, tags = ['priority' 'insured'] })) (nc/RequestOpts {
122 │ headers = { 'Content-Type' = 'application/json', 'Authorization' = (str/append 'Bearer ' alice_tok) }
123 │ timeout = 15s
124 │ })
125 │ if r_ord.status != 201 [ return (err 'taskflow: expected 201 on order creation') ]
126 │
127 │ // 3. Verify member cannot access /api/v1/admin/overview (403 role separation)
128 │ r_forbid = nc/request 'GET' (str/append base '/api/v1/admin/overview') (bytes/with-cap 0) (nc/RequestOpts {
129 │ headers = (nc/bearer-header alice_tok)
130 │ timeout = 15s
131 │ })
132 │ if r_forbid.status != 403 [ return (err 'taskflow: expected 403 on member -> admin route') ]
133 │
134 │ // 4. Sign in as Jordan Ops (admin) & deliver warehouse-packed webhook signal to ord-1001
135 │ r_adm = nc/post-json (str/append base '/api/v1/auth/login') { user_id = 'admin-ops', password = 'admin-pass' } def_opts
136 │ adm_tok = str/append '' (map/get (json/decode (bytes/to-str r_adm.body)) 'token')
137 │ r_sig = nc/request 'POST' (str/append base '/api/v1/admin/signal') (bytes/from-str (json/encode { order_id = 'ord-1001', box_code = 'BOX-42' })) (nc/RequestOpts {
138 │ headers = { 'Content-Type' = 'application/json', 'Authorization' = (str/append 'Bearer ' adm_tok) }
139 │ timeout = 15s
140 │ })
141 │ if r_sig.status != 200 [ return (err 'taskflow: expected 200 on admin signal') ]
142 │
143 │ // 5. Fetch Light-First /ui/portal HTML shell
144 │ r_ui = nc/get (str/append base '/ui/portal') def_opts
145 │ _ = task/await srv
146 │
147 │ // Verify Alice charged ONCE ($760) despite full workflow replay!
148 │ sum = st/read-self-summary store_path 'cust-alice'
149 │ bob_sum = st/read-self-summary store_path 'cust-bob'
150 │ if (as-i64 (map/get sum 'balance')) != 760 or (as-i64 (map/get bob_sum 'balance')) != 50 [
151 │ return (err 'taskflow: durable ledger balance invariant failed')
152 │ ]
153 │ ui_html = bytes/to-str r_ui.body
154 │ if not (str/contains? ui_html 'data-theme="light"') [
155 │ return (err 'taskflow: portal UI missing light-first theme')
156 │ ]
157 │ println (str/join [
158 │ '[TaskFlow Studio] alice=$760 bob=$50(compensated) ord-1001=completed'
159 │ ' rbac=200/403 ui=' (mold (len ui_html)) 'B'
160 │ ] '')
161 │ .ok
162 │ ]
163 │
164 │ main = fn [] any [
165 │ args = os/args
166 │ mut serve_port = ''
167 │ mut i = 0
168 │ while i < (len args) [
169 │ if args[i] == '--serve' [
170 │ serve_port = if (i + 1) < (len args) [ str/append '' args[i + 1] ] else [ '8095' ]
171 │ ]
172 │ i = i + 1
173 │ ]
174 │ if serve_port != '' [
175 │ live_store = 'dist/taskflow_studio_live.vkkv'
176 │ if not (os/exists? live_store) [ st/init-seed-data live_store ]
177 │ addr = str/append '127.0.0.1:' serve_port
178 │ println (str/append '[TaskFlow Studio] Live Web App -> http://' addr)
179 │ ln = inet/listen-nonblock addr
180 │ _ = web/serve-reactor ln (make-studio-app live_store) (web/AsyncServerOpts { max_requests = 0 })
181 │ _ = net/close ln
182 │ return .ok
183 │ ]
184 │
185 │ tmp_store = str/join [(os/temp-dir) '/veko_taskflow_studio.vkkv'] ''
186 │ defer [ _ = os/remove/or tmp_store [.ok] ]
187 │ run-e2e-verification tmp_store
188 │ ]
189 │
190 │ res = main
191 │ if err? res [
192 │ println (str/append 'FAIL: ' (mold res))
193 │ os/exit 1
194 │ ]