@nanobpm/urban 0.96.3 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +60 -0
  2. package/dist/runtime/connector-worker-sdk.d.ts +2 -0
  3. package/dist/runtime/connector-worker-sdk.js +6 -1
  4. package/dist/runtime/core/host.d.ts +15 -5
  5. package/dist/runtime/core/manifest.d.ts +23 -0
  6. package/dist/runtime/core/manifest.js +8 -0
  7. package/dist/runtime/core/modules/connectors.d.ts +3 -0
  8. package/dist/runtime/core/modules/connectors.js +32 -1
  9. package/dist/runtime/core/modules/formjs.gen.js +1 -1
  10. package/dist/runtime/core/modules/forms.d.ts +20 -0
  11. package/dist/runtime/core/modules/forms.js +47 -0
  12. package/dist/runtime/core/modules/pages.js +12 -1
  13. package/dist/runtime/core/modules/runtime.gen.js +1 -1
  14. package/dist/runtime/core/modules/surfaces.js +57 -4
  15. package/dist/runtime/core/modules/workers.js +5 -1
  16. package/dist/runtime/core/validate.js +12 -0
  17. package/dist/runtime/engine/nanosdk.d.ts +1 -0
  18. package/dist/runtime/engine/nanosdk.js +3 -0
  19. package/dist/runtime/index.d.ts +3 -3
  20. package/dist/runtime/index.js +1 -1
  21. package/package.json +2 -2
  22. package/src/runtime/browser/fake-dom.test-utils.ts +16 -1
  23. package/src/runtime/browser/formjs.browser.js +258 -7
  24. package/src/runtime/browser/formjs.browser.test.ts +690 -0
  25. package/src/runtime/browser/runtime.browser.js +25 -3
  26. package/src/runtime/browser/runtime.engineform.test.ts +203 -0
  27. package/src/runtime/connector-worker-sdk.test.ts +9 -0
  28. package/src/runtime/connector-worker-sdk.ts +8 -1
  29. package/src/runtime/core/host.ts +16 -1
  30. package/src/runtime/core/manifest.ts +28 -0
  31. package/src/runtime/core/modules/connectors.test.ts +158 -1
  32. package/src/runtime/core/modules/connectors.ts +44 -1
  33. package/src/runtime/core/modules/formjs.gen.ts +1 -1
  34. package/src/runtime/core/modules/forms.ts +47 -0
  35. package/src/runtime/core/modules/pages.test.ts +21 -0
  36. package/src/runtime/core/modules/pages.ts +13 -1
  37. package/src/runtime/core/modules/runtime.gen.ts +1 -1
  38. package/src/runtime/core/modules/surfaces.test.ts +308 -0
  39. package/src/runtime/core/modules/surfaces.ts +58 -4
  40. package/src/runtime/core/modules/workers.test.ts +45 -1
  41. package/src/runtime/core/modules/workers.ts +5 -1
  42. package/src/runtime/core/validate.test.ts +19 -0
  43. package/src/runtime/core/validate.ts +12 -0
  44. package/src/runtime/engine/nanosdk.test.ts +17 -0
  45. package/src/runtime/engine/nanosdk.ts +4 -1
  46. package/src/runtime/index.ts +3 -0
@@ -437,3 +437,311 @@ test("MCP is listed as an active surface only when config-enabled, but its route
437
437
  assert.ok(Array.isArray(offEnabled) && !offEnabled.includes("mcp@/app/mcp"), "a disabled MCP surface must not be listed as active");
438
438
  assert.ok(off.routes.some((r) => r.path === "/app/mcp"), "the MCP route stays mounted even when disabled");
439
439
  });
440
+
441
+ // ── #603: the inbox loads the task's variables and passes them to the renderer ─
442
+
443
+ test("/api/variables returns the task's variables as a {name: value} context", async () => {
444
+ let seenFilter: unknown;
445
+ const engine: EngineClient = {
446
+ ...fakeEngine,
447
+ searchVariables: async (filter) => {
448
+ seenFilter = filter;
449
+ return [
450
+ { variableKey: "v1", name: "title", value: JSON.stringify("Draft v2"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
451
+ { variableKey: "v2", name: "img1", value: JSON.stringify("data:image/png;base64,iVBORw0KGgo="), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
452
+ { variableKey: "v3", name: "count", value: "3", scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
453
+ ];
454
+ },
455
+ };
456
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/tasks" } }), appWith(engine));
457
+ const variables = s.routes.find(
458
+ (r) => r.source === "surface:taskInbox" && r.method === "GET" && r.path.endsWith("/api/variables"),
459
+ )!;
460
+ const res = await call(variables, { query: "processInstanceKey=pi-9" });
461
+ assert.deepEqual(seenFilter, { processInstanceKey: "pi-9" }, "the route searches the engine's variables by process instance");
462
+ assert.equal(res.status, 200);
463
+ assert.deepEqual(JSON.parse(String(res.body)), {
464
+ title: "Draft v2",
465
+ img1: "data:image/png;base64,iVBORw0KGgo=",
466
+ count: 3,
467
+ }, "serialized-JSON values arrive parsed (strings as strings, numbers as numbers)");
468
+ });
469
+
470
+ test("/api/variables 400s without a processInstanceKey", async () => {
471
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/tasks" } }), fakeApp);
472
+ const variables = s.routes.find(
473
+ (r) => r.source === "surface:taskInbox" && r.method === "GET" && r.path.endsWith("/api/variables"),
474
+ )!;
475
+ const res = await call(variables);
476
+ assert.equal(res.status, 400);
477
+ });
478
+
479
+ test("inbox client loads the task's variables and renders {{title}} + an =img1 image with them", async () => {
480
+ // The acceptance scenario: a task whose variables include `title` and `img1`,
481
+ // with a form using {{title}} and an image with source "=img1", renders both.
482
+ // The server half (the /api/variables route) is covered above; here we pin the
483
+ // CLIENT half: openForm must fetch the variables for the task's process
484
+ // instance and hand them to the shared renderer as its context.
485
+ const { page } = inboxRoutes(fakeEngine);
486
+ const rendered = String((await call(page)).body);
487
+ assert.ok(
488
+ rendered.includes("'/api/variables?processInstanceKey='+encodeURIComponent(t.processInstanceKey)"),
489
+ "openForm fetches the task's variables by its processInstanceKey",
490
+ );
491
+ assert.ok(rendered.includes("Promise.all(["), "form schema and variables load together");
492
+ assert.ok(rendered.includes("context:context||{}"), "the variables are passed to NanoFormJs.renderForm as its context");
493
+ // The renderer the page embeds must be the context-aware one: it templates
494
+ // {{name}} in text components, resolves =varName image sources, and prefills
495
+ // keyed inputs — all from that one context.
496
+ assert.ok(rendered.includes("function fjTemplate"), "embedded renderer has {{name}} text templating");
497
+ assert.ok(rendered.includes("function fjImageSrc"), "embedded renderer has the image source resolver");
498
+ assert.ok(rendered.includes("njf-image"), "page styles the image component");
499
+ });
500
+
501
+ test("inbox client degrades to an empty context when the variables fetch fails", async () => {
502
+ const { page } = inboxRoutes(fakeEngine);
503
+ const rendered = String((await call(page)).body);
504
+ // A failed variables fetch must not block the form: it falls back to {} so the
505
+ // schema still renders (untemplated/unprefilled).
506
+ assert.ok(
507
+ rendered.includes(".catch(()=>({}))"),
508
+ "a variables fetch failure degrades to an empty context rather than failing the form",
509
+ );
510
+ });
511
+
512
+ // ── PR #604 review: the variables context is process-scoped, complete, and name-safe ─
513
+
514
+ test("/api/variables uses only process-level variables — sibling task-local scopes never leak, in any order", async () => {
515
+ const rows = [
516
+ { variableKey: "a", name: "title", value: JSON.stringify("process"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
517
+ { variableKey: "b", name: "title", value: JSON.stringify("sibling-local"), scopeKey: "ei-1", processInstanceKey: "pi-9", isTruncated: false },
518
+ { variableKey: "c", name: "only", value: JSON.stringify("sibling-only"), scopeKey: "ei-2", processInstanceKey: "pi-9", isTruncated: false },
519
+ ];
520
+ for (const order of [rows, [...rows].reverse()]) {
521
+ const engine: EngineClient = { ...fakeEngine, searchVariables: async () => order };
522
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/tasks" } }), appWith(engine));
523
+ const route = s.routes.find((r) => r.source === "surface:taskInbox" && r.path.endsWith("/api/variables"))!;
524
+ const res = await call(route, { query: "processInstanceKey=pi-9" });
525
+ assert.deepEqual(JSON.parse(String(res.body)), { title: "process" });
526
+ }
527
+ });
528
+
529
+ test("/api/variables omits truncated previews so they can never be prefilled and submitted", async () => {
530
+ const engine: EngineClient = {
531
+ ...fakeEngine,
532
+ searchVariables: async () => [
533
+ { variableKey: "a", name: "big", value: JSON.stringify("clipped…"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: true },
534
+ { variableKey: "b", name: "small", value: JSON.stringify("ok"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
535
+ ],
536
+ };
537
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/tasks" } }), appWith(engine));
538
+ const route = s.routes.find((r) => r.source === "surface:taskInbox" && r.path.endsWith("/api/variables"))!;
539
+ const res = await call(route, { query: "processInstanceKey=pi-9" });
540
+ assert.deepEqual(JSON.parse(String(res.body)), { small: "ok" });
541
+ });
542
+
543
+ test("/api/variables round-trips a variable named __proto__ as data", async () => {
544
+ for (const value of ["scalar", { nested: 1 }]) {
545
+ const engine: EngineClient = {
546
+ ...fakeEngine,
547
+ searchVariables: async () => [
548
+ { variableKey: "a", name: "__proto__", value: JSON.stringify(value), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
549
+ ],
550
+ };
551
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/tasks" } }), appWith(engine));
552
+ const route = s.routes.find((r) => r.source === "surface:taskInbox" && r.path.endsWith("/api/variables"))!;
553
+ const res = await call(route, { query: "processInstanceKey=pi-9" });
554
+ const parsed = JSON.parse(String(res.body));
555
+ assert.ok(Object.hasOwn(parsed, "__proto__"));
556
+ assert.deepEqual(parsed.__proto__, value);
557
+ }
558
+ });
559
+
560
+ // ── PR #604 round 4: inbox image URLs rebase onto the APP mount, not the inbox route ──
561
+
562
+ test("inbox client rebases image URLs onto the app mount (inbox route stripped), direct and proxied", async () => {
563
+ const { page } = inboxRoutes(fakeEngine);
564
+ const rendered = String((await call(page)).body);
565
+ // The image resolver must NOT reuse BASE: BASE includes the inbox route
566
+ // (location.pathname is ".../tasks"), so `/app/thumb.png` would become
567
+ // `/tasks/app/thumb.png` — the inbox route has no /app handler, so the image
568
+ // 404s. The client derives a separate app-mount prefix by stripping the
569
+ // configured inbox route's segments, and the resolver prefixes THAT.
570
+ assert.match(
571
+ rendered,
572
+ /const APP_BASE=BASE\.split\('\/'\)\.slice\(0,-INBOX_SEGMENTS\)\.join\('\/'\)/,
573
+ "client derives the app mount by stripping the inbox route's segments from BASE",
574
+ );
575
+ assert.match(
576
+ rendered,
577
+ /resolveUrl:\(u\)=>u\.startsWith\('\/\/'\)\|\|\/\^\[a-zA-Z\]\[a-zA-Z0-9\+\.-\]\*:\/\.test\(u\)\?u:u\.startsWith\('\/'\)\?APP_BASE\+u:APP_BASE\+'\/'\+u/,
578
+ "image resolver prefixes the app mount, not the inbox route",
579
+ );
580
+ // Direct deployment: page served at /tasks → BASE="/tasks", APP_BASE="".
581
+ // Proxied: page at /console/app-view/<name>/tasks → APP_BASE="/console/app-view/<name>".
582
+ // Both reduce to the same derivation; pin the behaviour with the derivation the
583
+ // client ships (the default inbox path is single-segment):
584
+ const derive = (pathname: string) => {
585
+ const base = pathname.replace(/[/]+$/, "");
586
+ const appBase = base.split("/").slice(0, -1).join("/");
587
+ const resolveUrl = (u: string) => (u.startsWith("//") ? u : u.startsWith("/") ? appBase + u : appBase + "/" + u);
588
+ return resolveUrl(u0);
589
+ };
590
+ const u0 = "/app/thumb.png";
591
+ assert.equal(derive("/tasks"), "/app/thumb.png", "direct: the image URL keeps no inbox segment");
592
+ assert.equal(
593
+ derive("/console/app-view/my-app/tasks"),
594
+ "/console/app-view/my-app/app/thumb.png",
595
+ "proxied: the proxy prefix is kept, the inbox route is dropped",
596
+ );
597
+ // API fetches still use the inbox route (BASE) — only image rebasing moves to APP_BASE.
598
+ assert.match(rendered, /fetch\(BASE\+path/, "api() still fetches under the inbox route");
599
+ });
600
+
601
+ // ── PR #604 round 5: APP_BASE strips the ENTIRE configured inbox path ──
602
+
603
+ test("inbox client derives APP_BASE from the configured inbox path's segment count (nested paths)", async () => {
604
+ const { page } = inboxRoutes(fakeEngine);
605
+ const rendered = String((await call(page)).body);
606
+ // Stripping ONE trailing segment only works for a single-segment inbox path:
607
+ // a configured nested path like /review/tasks would leave "/review" behind, so
608
+ // /app/thumb.png resolves to /review/app/thumb.png (no handler — 404), and the
609
+ // console proxy keeps the unwanted segment too. The client must strip as many
610
+ // segments as the CONFIGURED inbox path has — numeric page metadata, not an
611
+ // embedded path string (nothing manifest-supplied becomes markup/JS text).
612
+ assert.match(
613
+ rendered,
614
+ /const INBOX_SEGMENTS=\d+;/,
615
+ "the inbox path's segment count is embedded as numeric metadata",
616
+ );
617
+ assert.match(
618
+ rendered,
619
+ /const APP_BASE=BASE\.split\('\/'\)\.slice\(0,-INBOX_SEGMENTS\)\.join\('\/'\)/,
620
+ "APP_BASE strips exactly INBOX_SEGMENTS segments from BASE",
621
+ );
622
+ // Pin the behaviour with the derivation the client ships, direct and proxied,
623
+ // for single-segment AND nested inbox paths:
624
+ const derive = (pathname: string, segments: number) => {
625
+ const base = pathname.replace(/[/]+$/, "");
626
+ const appBase = base.split("/").slice(0, -segments).join("/");
627
+ const resolveUrl = (u: string) => (u.startsWith("//") ? u : u.startsWith("/") ? appBase + u : appBase + "/" + u);
628
+ return resolveUrl(u0);
629
+ };
630
+ const u0 = "/app/thumb.png";
631
+ assert.equal(derive("/tasks", 1), "/app/thumb.png", "direct, single-segment inbox path");
632
+ assert.equal(
633
+ derive("/console/app-view/my-app/tasks", 1),
634
+ "/console/app-view/my-app/app/thumb.png",
635
+ "proxied, single-segment inbox path",
636
+ );
637
+ assert.equal(derive("/review/tasks", 2), "/app/thumb.png", "direct, nested inbox path — no /review retained");
638
+ assert.equal(
639
+ derive("/console/app-view/my-app/review/tasks", 2),
640
+ "/console/app-view/my-app/app/thumb.png",
641
+ "proxied, nested inbox path — the proxy prefix is kept, the whole inbox route is dropped",
642
+ );
643
+ });
644
+
645
+ test("inbox page embeds the configured inbox path's segment count, not the path string", async () => {
646
+ // A nested configured path contributes exactly its segment count as metadata —
647
+ // the path STRING itself is never embedded (the manifest→<script> injection
648
+ // surface stays closed).
649
+ for (const [path, segments] of [["/tasks", 1], ["/review/tasks", 2], ["/a/b/c", 3]] as const) {
650
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path } }), appWith(fakeEngine));
651
+ const page = s.routes.find((r) => r.source === "surface:taskInbox" && r.method === "GET" && !r.path.includes("/api/"))!;
652
+ const body = String((await call(page)).body);
653
+ assert.ok(body.includes(`const INBOX_SEGMENTS=${segments};`), `${path} → INBOX_SEGMENTS=${segments}`);
654
+ if (path !== "/tasks") {
655
+ assert.ok(!body.includes(path), `the path string ${path} is not embedded`);
656
+ }
657
+ }
658
+ });
659
+
660
+ // ── PR #604 round 7: repeated-slash inbox paths; relative image sources rebase too ──
661
+
662
+ test("inbox client counts repeated-slash slots when deriving the app base", async () => {
663
+ // normalizeRoutePath collapses LEADING slashes and drops trailing ones but
664
+ // preserves INTERIOR repeated slashes (router.ts), so a configured
665
+ // "/review//tasks" is served verbatim. The page's BASE.split('/') then retains
666
+ // the empty slot the double slash produces — the server-side segment count
667
+ // must count the SAME slots, or the client strips too few and APP_BASE keeps
668
+ // a segment that is not the app mount ("/review" instead of "").
669
+ const s = mountSurfaces(ctxWith({ taskInbox: { enabled: true, path: "/review//tasks" } }), appWith(fakeEngine));
670
+ const page = s.routes.find((r) => r.source === "surface:taskInbox" && r.method === "GET" && !r.path.includes("/api/"))!;
671
+ const body = String((await call(page)).body);
672
+ // "/review//tasks".split("/") → ["", "review", "", "tasks"] — 3 slots after the
673
+ // leading slash, so the client must strip 3 (not the 2 non-empty segments).
674
+ assert.ok(body.includes("const INBOX_SEGMENTS=3;"), "the repeated-slash slot is counted (3, not 2)");
675
+ // Pin the derivation the client ships: BASE.split('/').slice(0,-INBOX_SEGMENTS).
676
+ const derive = (pathname: string, segments: number) => {
677
+ const base = pathname.replace(/[/]+$/, "");
678
+ return base.split("/").slice(0, -segments).join("/");
679
+ };
680
+ assert.equal(derive("/review//tasks", 3), "", "direct: the whole inbox route is stripped");
681
+ assert.equal(
682
+ derive("/console/app-view/my-app/review//tasks", 3),
683
+ "/console/app-view/my-app",
684
+ "proxied: only the proxy prefix remains",
685
+ );
686
+ // …whereas the old non-empty-segment count (2) would retain "/review".
687
+ assert.equal(derive("/review//tasks", 2), "/review", "the wrong count retains a bogus segment");
688
+ });
689
+
690
+ test("inbox client rebases scheme-less RELATIVE image sources onto the app mount", async () => {
691
+ const { page } = inboxRoutes(fakeEngine);
692
+ const rendered = String((await call(page)).body);
693
+ // A source like "app/thumb.png" (no leading slash) is a scheme-less RELATIVE
694
+ // path: left unchanged, the browser resolves it against the page URL, so a
695
+ // nested inbox path (/review/tasks) requests /review/app/thumb.png — the inbox
696
+ // route has no such handler (404). The resolver must rebase it onto APP_BASE
697
+ // exactly like a root-relative source, while absolute http(s)/data: URLs still
698
+ // pass through untouched.
699
+ // Test the resolver the client ACTUALLY ships (extracted from the page), not a
700
+ // re-implementation that could drift from it.
701
+ const m = /resolveUrl:(\(u\)=>[^\n]*?),\n/.exec(rendered);
702
+ assert.ok(m, "the inbox page wires a resolveUrl");
703
+ const src = m[1];
704
+ const resolve = (appBase: string): ((u: string) => string) => new Function("APP_BASE", `return ${src};`)(appBase);
705
+ // Scheme-bearing (absolute) sources must pass through verbatim — never rebased
706
+ // into a bogus '/https://…' app path.
707
+ for (const base of ["", "/console/app-view/my-app"]) {
708
+ for (const abs of ["https://cdn.example.com/t.png", "http://x.example/t.png", "data:image/png;base64,iVBORw0KGgo="]) {
709
+ assert.equal(resolve(base)(abs), abs, `absolute ${abs} passes through under APP_BASE='${base}'`);
710
+ }
711
+ }
712
+ const direct = resolve(""); // inbox at /review/tasks → APP_BASE ""
713
+ assert.equal(direct("app/thumb.png"), "/app/thumb.png", "direct: a relative source lands on the app route, not /review/app/…");
714
+ assert.equal(direct("/app/thumb.png"), "/app/thumb.png", "direct: a root-relative source is unchanged");
715
+ const proxied = resolve("/console/app-view/my-app");
716
+ assert.equal(
717
+ proxied("app/thumb.png"),
718
+ "/console/app-view/my-app/app/thumb.png",
719
+ "proxied: a relative source lands under the app mount",
720
+ );
721
+ assert.equal(
722
+ proxied("/app/thumb.png"),
723
+ "/console/app-view/my-app/app/thumb.png",
724
+ "proxied: a root-relative source still rebases onto the app mount",
725
+ );
726
+ // End-to-end: the shipped resolver followed by the renderer's post-resolution
727
+ // allowlist keeps absolute https/data: sources intact and rejects '//host'.
728
+ const allowlist = (u: string) =>
729
+ /[\s\u0000-\u001f\u007f\\]/.test(u)
730
+ ? null
731
+ : /^data:image\/(png|jpeg|gif|webp)[;,]/i.test(u)
732
+ ? u
733
+ : /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(u)
734
+ ? /^https?:\/\//i.test(u) ? u : null
735
+ : u.startsWith("//") ? null : u;
736
+ const pipeline = (u: string) => {
737
+ const out = allowlist(resolve("/console/app-view/my-app")(u));
738
+ return out;
739
+ };
740
+ assert.equal(pipeline("https://cdn.example.com/t.png"), "https://cdn.example.com/t.png", "absolute https survives the pipeline");
741
+ assert.equal(
742
+ pipeline("data:image/png;base64,iVBORw0KGgo="),
743
+ "data:image/png;base64,iVBORw0KGgo=",
744
+ "a data:image source survives the pipeline",
745
+ );
746
+ assert.equal(pipeline("//evil.example.com/x.png"), null, "protocol-relative is rejected before the resolver runs");
747
+ });
@@ -10,7 +10,7 @@
10
10
  import type { AppApi, RuntimeContext } from "../context.ts";
11
11
  import { html, json, normalizeRoutePath, type Route } from "../router.ts";
12
12
  import { FORMJS_JS } from "./formjs.gen.ts";
13
- import { completeUserTaskResponse, resolveFormResponse } from "./forms.ts";
13
+ import { completeUserTaskResponse, resolveFormResponse, taskVariablesResponse } from "./forms.ts";
14
14
  import { mountActions } from "./actions.ts";
15
15
  import { mountAgent } from "./agent.ts";
16
16
  import { mountApi } from "./api.ts";
@@ -30,7 +30,7 @@ export interface SurfacesHandle {
30
30
  describe(): Record<string, unknown>;
31
31
  }
32
32
 
33
- function inboxPage(): string {
33
+ function inboxPage(inboxBase: string): string {
34
34
  // Reverse-proxy safe: the client derives its API base from location.pathname
35
35
  // (where THIS page was actually served) rather than an embedded absolute
36
36
  // route base. A hardcoded "/tasks" would escape the Nano console's
@@ -39,6 +39,20 @@ function inboxPage(): string {
39
39
  // <script> injection surface entirely: nothing manifest-supplied is embedded.
40
40
  // All task/form values are rendered via textContent / setAttribute — never
41
41
  // innerHTML — so nothing the engine returns can inject markup.
42
+ //
43
+ // The ONE manifest-derived value the page does embed is the configured inbox
44
+ // path's SEGMENT COUNT — numeric metadata, never the path string, so the
45
+ // injection surface stays closed. The client strips that many segments from
46
+ // BASE to derive the app mount: stripping a fixed single segment would retain
47
+ // a nested configured path (an inbox mounted at review+tasks would rebase
48
+ // '/app/thumb.png' to '…/review/app/thumb.png', which has no handler).
49
+ // normalizeRoutePath guarantees a leading slash and no trailing one, but
50
+ // PRESERVES interior repeated slashes (router.ts) — so count every slot the
51
+ // client's BASE.split('/') produces after the leading slash (split.length - 1),
52
+ // including the empty slots a configured '/review//tasks' yields. Counting only
53
+ // non-empty segments would strip too few: the client's split retains the empty
54
+ // slot, so APP_BASE would keep a segment that is not the app mount.
55
+ const inboxSegments = inboxBase.split("/").length - 1;
42
56
  return `<!doctype html><meta charset="utf-8"><title>Task inbox</title>
43
57
  <style>body{font:14px system-ui,sans-serif;margin:2rem;max-width:52rem}
44
58
  ul{list-style:none;padding:0}li{margin:.4rem 0;display:flex;align-items:center;gap:.5rem}
@@ -48,6 +62,7 @@ button{font:inherit;padding:.2rem .6rem;cursor:pointer}
48
62
  .njf-field input,.njf-field textarea,.njf-field select{font:inherit;padding:.3rem;width:100%;box-sizing:border-box;max-width:24rem}
49
63
  .njf-field input[type=checkbox],.njf-field input[type=radio]{width:auto}
50
64
  .njf-actions{margin-top:.6rem}
65
+ .njf-image{display:block;max-width:100%;height:auto;margin:.6rem 0}
51
66
  #form{margin-top:1.5rem;border-top:1px solid #ddd;padding-top:1rem}
52
67
  .muted{color:#666}</style>
53
68
  <h1>Task inbox</h1><ul id="tasks"><li>loading…</li></ul>
@@ -55,6 +70,16 @@ button{font:inherit;padding:.2rem .6rem;cursor:pointer}
55
70
  <script>${FORMJS_JS}</script>
56
71
  <script>
57
72
  const BASE=location.pathname.replace(/[/]+$/,'');
73
+ // The app-mount prefix: BASE ends with the WHOLE configured inbox route (this
74
+ // page IS the inbox), so strip exactly that many segments — not a fixed one, or
75
+ // a nested inbox path (e.g. review+tasks) would leave its leading segments
76
+ // behind and '/app/thumb.png' would resolve under them (no handler there).
77
+ // Root-relative APP paths ('/app/…') rebase onto APP_BASE — not BASE — otherwise
78
+ // the URL keeps the inbox route ('/tasks/app/…'). Direct run: BASE='/tasks' →
79
+ // APP_BASE=''. Proxied: BASE='/console/app-view/<name>/tasks' →
80
+ // APP_BASE='/console/app-view/<name>'.
81
+ const INBOX_SEGMENTS=${inboxSegments};
82
+ const APP_BASE=BASE.split('/').slice(0,-INBOX_SEGMENTS).join('/');
58
83
  const tasksEl=document.getElementById('tasks');
59
84
  const formEl=document.getElementById('form');
60
85
 
@@ -84,7 +109,16 @@ function loadTasks(){
84
109
  function openForm(t){
85
110
  formEl.replaceChildren(el('p',{class:'muted'},'loading form…'));
86
111
  const q='formKey='+encodeURIComponent(t.formKey);
87
- api('/api/form?'+q).then(f=>{
112
+ // Load the form schema AND the task's variables together (#603): the variables
113
+ // are the renderer's context — {{name}} text templating, =varName image
114
+ // sources, and keyed-input prefill all resolve against them, so the reviewer
115
+ // sees what they are reviewing. A variables fetch that fails degrades to an
116
+ // empty context (the form still renders, untemplated/unprefilled) rather than
117
+ // blocking the form.
118
+ const varsP=t.processInstanceKey
119
+ ?api('/api/variables?processInstanceKey='+encodeURIComponent(t.processInstanceKey)).catch(()=>({}))
120
+ :Promise.resolve({});
121
+ Promise.all([api('/api/form?'+q),varsP]).then(([f,context])=>{
88
122
  formEl.replaceChildren();
89
123
  if(!f||!f.schema){renderNoForm(t);return;}
90
124
  // Reuse the ONE shared form-js renderer (NanoFormJs) — no fork with the pages surface.
@@ -92,6 +126,16 @@ function openForm(t){
92
126
  heading:'Task '+(t.elementId||t.userTaskKey),
93
127
  submitLabel:'Submit',
94
128
  cancelLabel:'Cancel',
129
+ context:context||{},
130
+ // Rebase root-relative image sources ('/app/…' — any single-leading-slash app
131
+ // path) onto the APP mount (APP_BASE = BASE minus the inbox route), so they
132
+ // survive the console's path-prefixed proxy without keeping the inbox segment.
133
+ // A scheme-less RELATIVE source ('app/thumb.png') would otherwise resolve
134
+ // against the page URL — under a nested inbox mount that requests
135
+ // <inbox>/app/thumb.png, which has no handler — so rebase those onto
136
+ // APP_BASE too. Any scheme-bearing source (http(s):, data:) and a protocol-relative
137
+ // '//host' (already rejected by the renderer's allowlist) pass through verbatim.
138
+ resolveUrl:(u)=>u.startsWith('//')||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(u)?u:u.startsWith('/')?APP_BASE+u:APP_BASE+'/'+u,
95
139
  onSubmit:(variables)=>complete(t.userTaskKey,variables),
96
140
  onCancel:loadTasks,
97
141
  }));
@@ -132,7 +176,7 @@ export function mountSurfaces(ctx: RuntimeContext, app: AppApi): SurfacesHandle
132
176
  method: "GET",
133
177
  path: base,
134
178
  source: "surface:taskInbox",
135
- handler: () => html(inboxPage()),
179
+ handler: () => html(inboxPage(base)),
136
180
  });
137
181
  routes.push({
138
182
  method: "GET",
@@ -163,6 +207,16 @@ export function mountSurfaces(ctx: RuntimeContext, app: AppApi): SurfacesHandle
163
207
  handler: async (req) =>
164
208
  resolveFormResponse(app.engine, req.query.get("formKey") ?? undefined, req.query.get("formId") ?? undefined),
165
209
  });
210
+ // The task's variables (#603) — the render context the shared form-js renderer
211
+ // templates/prefills from. Same source as the pages surface's variables route
212
+ // (forms.ts `taskVariablesResponse`), so the two can never drift.
213
+ routes.push({
214
+ method: "GET",
215
+ path: `${base}/api/variables`,
216
+ source: "surface:taskInbox",
217
+ handler: async (req) =>
218
+ taskVariablesResponse(app.engine, req.query.get("processInstanceKey") ?? undefined),
219
+ });
166
220
  routes.push({
167
221
  method: "POST",
168
222
  path: `${base}/api/complete`,
@@ -23,6 +23,11 @@ import { join } from "node:path";
23
23
  /** A tiny engine that records registrations and can deliver a job to a handler. */
24
24
  class MiniEngine implements EngineClient {
25
25
  workers = new Map<string, JobHandler>();
26
+ /** The options each `registerWorker` call carried, keyed by job type. */
27
+ workerOptions = new Map<
28
+ string,
29
+ { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] } | undefined
30
+ >();
26
31
  async deployResources(): Promise<{ deployed: number }> { return { deployed: 0 }; }
27
32
  async createInstance(): Promise<{ processInstanceKey: string }> { return { processInstanceKey: "pi" }; }
28
33
  async cancelInstance(): Promise<void> {}
@@ -46,8 +51,13 @@ class MiniEngine implements EngineClient {
46
51
  async updateJobRetries(): Promise<void> {}
47
52
  async setVariables(): Promise<void> {}
48
53
  async close(): Promise<void> {}
49
- async registerWorker(jobType: string, handler: JobHandler): Promise<WorkerSubscription> {
54
+ async registerWorker(
55
+ jobType: string,
56
+ handler: JobHandler,
57
+ options?: { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] },
58
+ ): Promise<WorkerSubscription> {
50
59
  this.workers.set(jobType, handler);
60
+ this.workerOptions.set(jobType, options);
51
61
  return { jobType, unsubscribe: async () => void this.workers.delete(jobType) };
52
62
  }
53
63
  deliver(jobType: string, job: EngineJob) {
@@ -226,6 +236,40 @@ test("mountWorkers silently skips a connector-backed worker (mountConnectors own
226
236
  assert.ok(!logs.some((l) => l.msg.includes("neither a handler nor an llm")));
227
237
  });
228
238
 
239
+ test("mountWorkers passes a worker's declared job lock timeout (timeoutMs) to registerWorker (issue #596)", async () => {
240
+ const engine = new MiniEngine();
241
+ const { ctx } = makeCtx(
242
+ {
243
+ workers: [
244
+ { taskType: "transcribe", handler: "workers/transcribe.ts", timeoutMs: 600_000 },
245
+ { taskType: "quick", handler: "workers/quick.ts" },
246
+ ],
247
+ llm: { fast: { provider: "env", model: "${NANO_APP_LLM_MODEL}" } },
248
+ },
249
+ engine,
250
+ );
251
+ ctx.host.importModule = async () => ({ default: () => ({}) });
252
+ await mountWorkers(ctx, makeApp());
253
+ assert.equal(engine.workerOptions.get("transcribe")?.timeoutMs, 600_000);
254
+ // A worker with no declared timeout leaves the engine/SDK default lock in place.
255
+ assert.equal(engine.workerOptions.get("quick")?.timeoutMs, undefined);
256
+ });
257
+
258
+ test("mountWorkers passes an llm worker's declared timeoutMs to registerWorker (issue #596)", async () => {
259
+ const engine = new MiniEngine();
260
+ const { ctx } = makeCtx(
261
+ {
262
+ workers: [{ taskType: "summarize", llm: "fast", timeoutMs: 300_000 }],
263
+ llm: { fast: { provider: "env", model: "${NANO_APP_LLM_MODEL}" } },
264
+ },
265
+ engine,
266
+ );
267
+ await withFetch("{}", async () => {
268
+ await mountWorkers(ctx, makeApp());
269
+ });
270
+ assert.equal(engine.workerOptions.get("summarize")?.timeoutMs, 300_000);
271
+ });
272
+
229
273
  test("mountWorkers binds the job's correlation context onto the handler's app.log", async () => {
230
274
  const engine = new MiniEngine();
231
275
  const { ctx } = makeCtx({ workers: [{ taskType: "charge", handler: "workers/charge.ts" }] }, engine);
@@ -5,7 +5,7 @@
5
5
  import type { AppApi, Mounted, RuntimeContext } from "../context.ts";
6
6
  import { isRecord } from "../guards.ts";
7
7
  import type { EngineJob, JobHandler, WorkerSubscription } from "../host.ts";
8
- import { workerJobType, type Worker } from "../manifest.ts";
8
+ import { workerJobType, workerTimeoutMs, type Worker } from "../manifest.ts";
9
9
  import { type DecisionEvaluator, type LlmRuntime, runLlmJob } from "./llm.ts";
10
10
  import { runInJobContext } from "../execContext.ts";
11
11
  import type { JobExecContext } from "../execContext.ts";
@@ -326,6 +326,8 @@ export async function mountWorkers(
326
326
  };
327
327
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
328
328
  workerName: `${ctx.manifest.id}:${jobType}`,
329
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
330
+ timeoutMs: workerTimeoutMs(decl),
329
331
  });
330
332
  subs.push(sub);
331
333
  jobTypes.push(jobType);
@@ -349,6 +351,8 @@ export async function mountWorkers(
349
351
  };
350
352
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
351
353
  workerName: `${ctx.manifest.id}:${jobType}`,
354
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
355
+ timeoutMs: workerTimeoutMs(decl),
352
356
  });
353
357
  subs.push(sub);
354
358
  jobTypes.push(jobType);
@@ -100,6 +100,25 @@ test("an llm-backed worker (no handler) is accepted", () => {
100
100
  assert.ok(!issues.some((i) => i.path.startsWith("workers[0]")));
101
101
  });
102
102
 
103
+ test("a worker job lock timeout (timeoutMs) must be a positive integer (issue #596)", () => {
104
+ const ok = collectManifestIssues({
105
+ ...valid,
106
+ workers: [{ taskType: "a.b", handler: "workers/x.ts", timeoutMs: 600_000 }],
107
+ });
108
+ assert.ok(!ok.some((i) => i.path.startsWith("workers[0]")));
109
+
110
+ for (const bad of [0, -5, 1.5, Number.NaN, "600000"]) {
111
+ const issues = collectManifestIssues({
112
+ ...valid,
113
+ workers: [{ taskType: "a.b", handler: "workers/x.ts", timeoutMs: bad }],
114
+ });
115
+ assert.ok(
116
+ issues.some((i) => i.path === "workers[0].timeoutMs"),
117
+ `timeoutMs=${String(bad)} must be rejected`,
118
+ );
119
+ }
120
+ });
121
+
103
122
  test("data.default must reference an existing source", () => {
104
123
  const issues = collectManifestIssues({
105
124
  ...valid,
@@ -144,6 +144,18 @@ export function collectManifestIssues(m: unknown): ValidationIssue[] {
144
144
  });
145
145
  }
146
146
  }
147
+ // The pending-schema job lock timeout (issue #596): when present it must be a
148
+ // positive integer of ms — a zero/negative lock would expire instantly (the job
149
+ // re-activated mid-handler), and a non-integer is a manifest typo to fail fast on.
150
+ if (worker !== undefined && "timeoutMs" in worker) {
151
+ const t = worker.timeoutMs;
152
+ if (typeof t !== "number" || !Number.isInteger(t) || t <= 0) {
153
+ issues.push({
154
+ path: `workers[${i}].timeoutMs`,
155
+ message: "timeoutMs must be a positive integer (ms)",
156
+ });
157
+ }
158
+ }
147
159
  });
148
160
  }
149
161
 
@@ -1211,6 +1211,23 @@ test("registerWorker creates a worker the SDK auto-starts, and dispatches + comp
1211
1211
  assert.equal(rec.stopped, 1);
1212
1212
  });
1213
1213
 
1214
+ test("registerWorker passes the job lock timeout through to createJobWorker (issue #596)", async () => {
1215
+ const client = fakeSdkClient();
1216
+ const engine = new SdkEngineClient(client);
1217
+ await engine.registerWorker("svc", () => ({}), { timeoutMs: 600_000 });
1218
+ const rec = client.workers[0];
1219
+ assert.equal(rec.cfg.jobTimeoutMs, 600_000);
1220
+ });
1221
+
1222
+ test("registerWorker leaves jobTimeoutMs unset (SDK default lock) when no timeoutMs is given", async () => {
1223
+ const client = fakeSdkClient();
1224
+ const engine = new SdkEngineClient(client);
1225
+ await engine.registerWorker("svc", () => ({}));
1226
+ const rec = client.workers[0];
1227
+ assert.equal(rec.cfg.jobTimeoutMs, undefined);
1228
+ assert.equal("jobTimeoutMs" in rec.cfg, false);
1229
+ });
1230
+
1214
1231
  test("registerWorker fails the job when the handler throws", async () => {
1215
1232
  const client = fakeSdkClient();
1216
1233
  const engine = new SdkEngineClient(client);
@@ -1366,12 +1366,15 @@ export class SdkEngineClient implements EngineClient {
1366
1366
  async registerWorker(
1367
1367
  jobType: string,
1368
1368
  handler: JobHandler,
1369
- options?: { workerName?: string; maxParallelJobs?: number; fetchVariables?: string[] },
1369
+ options?: { workerName?: string; maxParallelJobs?: number; timeoutMs?: number; fetchVariables?: string[] },
1370
1370
  ): Promise<WorkerSubscription> {
1371
1371
  const worker = this.client.createJobWorker({
1372
1372
  jobType,
1373
1373
  workerName: options?.workerName ?? `urban:${jobType}`,
1374
1374
  maxParallelJobs: options?.maxParallelJobs ?? 8,
1375
+ // The job lock timeout (issue #596): pass it through only when declared, so an
1376
+ // undeclared worker keeps the SDK's default lock rather than an explicit value.
1377
+ ...(options?.timeoutMs !== undefined ? { jobTimeoutMs: options.timeoutMs } : {}),
1375
1378
  fetchVariables: options?.fetchVariables,
1376
1379
  jobHandler: async (job) => {
1377
1380
  const rawKey = job.jobKey;
@@ -50,6 +50,7 @@ export {
50
50
  resolveBindHost,
51
51
  resolveBindMode,
52
52
  workerJobType,
53
+ workerTimeoutMs,
53
54
  ALL_INTERFACES_HOST,
54
55
  BIND_ENV_VAR,
55
56
  LOOPBACK_HOST,
@@ -70,6 +71,7 @@ export type {
70
71
  TaskInboxSurface,
71
72
  Trigger,
72
73
  Worker,
74
+ WorkerDecl,
73
75
  } from "./core/manifest.ts";
74
76
 
75
77
  // Validation
@@ -112,6 +114,7 @@ export type {
112
114
  ProcessDefinitionIdentity,
113
115
  ProcessInstanceSnapshot,
114
116
  ProcessInstanceState,
117
+ RegisterWorkerOptions,
115
118
  SqliteDb,
116
119
  UserTaskState,
117
120
  UserTaskSummary,