@studio8collective/patent-render 1.0.0 → 1.1.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.
package/dist/index.js CHANGED
@@ -1,137 +1,192 @@
1
1
  "use client";
2
2
 
3
3
  // ../../src/patent-render/client/PatentRender.tsx
4
- import { useEffect as useEffect6, useMemo as useMemo5, useRef as useRef6 } from "react";
4
+ import { useEffect as useEffect6, useLayoutEffect as useLayoutEffect3, useMemo as useMemo5, useRef as useRef7 } from "react";
5
5
 
6
6
  // ../../src/patent-render/schema/document.ts
7
+ import { z as z2 } from "zod";
8
+
9
+ // ../../src/patent-render/schema/plan.ts
7
10
  import { z } from "zod";
11
+ var FigureType = z.enum([
12
+ "flowchart",
13
+ "blockDiagram",
14
+ "mechanical2d",
15
+ "uiScreen",
16
+ "perspective3d",
17
+ "circuit",
18
+ "chemical"
19
+ ]);
20
+ var FigurePlan = z.object({
21
+ figureType: FigureType,
22
+ /** e.g. "Cross-sectional view taken along line A-A of FIG. 2" */
23
+ view: z.string(),
24
+ summary: z.string(),
25
+ /**
26
+ * Full generation spec: overall form and proportions (mm), every component's
27
+ * shape, position and relationships, counts, surface details and what faces
28
+ * the viewer. Written so a draftsperson can draw without guessing.
29
+ */
30
+ spec: z.string().default(""),
31
+ components: z.array(z.object({
32
+ numeral: z.string(),
33
+ name: z.string(),
34
+ description: z.string().optional(),
35
+ reused: z.boolean().default(false)
36
+ // numeral came from the host registry
37
+ })),
38
+ layers: z.array(z.object({ id: z.string(), name: z.string() })),
39
+ notes: z.array(z.string()).default([])
40
+ });
41
+ var DrawingStyle = z.enum(["standard", "detailed", "minimal"]);
42
+ var STYLE_LABEL = {
43
+ standard: { label: "Standard line art", hint: "Clean outlines and key details, as most filings" },
44
+ detailed: { label: "Detailed rendering", hint: "Shading strokes, glare, textures, fine features" },
45
+ minimal: { label: "Minimal outline", hint: "Essential outlines only, fewest lines" }
46
+ };
47
+ var GenerationPrefs = z.object({
48
+ figureType: FigureType.optional(),
49
+ // undefined = let the planner decide
50
+ style: DrawingStyle.default("standard")
51
+ });
52
+ var FIGURE_TYPE_LABEL = {
53
+ flowchart: "Flowchart",
54
+ blockDiagram: "Block diagram",
55
+ mechanical2d: "Mechanical 2D",
56
+ uiScreen: "UI screen",
57
+ perspective3d: "Perspective 3D",
58
+ circuit: "Circuit",
59
+ chemical: "Chemical structure"
60
+ };
61
+
62
+ // ../../src/patent-render/schema/document.ts
8
63
  function vec(n) {
9
- return z.array(z.number()).length(n);
64
+ return z2.array(z2.number()).length(n);
10
65
  }
11
66
  var Point = vec(2);
12
- var StrokeStyle = z.enum(["solid", "dashed", "centre", "phantom"]);
13
- var Stroke = z.object({
14
- width: z.number().positive().default(0.35),
67
+ var StrokeStyle = z2.enum(["solid", "dashed", "centre", "phantom"]);
68
+ var Stroke = z2.object({
69
+ width: z2.number().positive().default(0.35),
15
70
  style: StrokeStyle.default("solid")
16
71
  });
17
- var Fill = z.enum(["none", "black", "white"]);
72
+ var Fill = z2.enum(["none", "black", "white"]);
18
73
  var base = {
19
- id: z.string().min(1),
20
- name: z.string().optional(),
74
+ id: z2.string().min(1),
75
+ name: z2.string().optional(),
21
76
  /** Degrees, clockwise, about the item's bounding-box centre. */
22
- rotation: z.number().default(0),
23
- locked: z.boolean().default(false),
24
- hidden: z.boolean().default(false)
77
+ rotation: z2.number().default(0),
78
+ locked: z2.boolean().default(false),
79
+ hidden: z2.boolean().default(false)
25
80
  };
26
81
  var stroked = { stroke: Stroke.default({ width: 0.35, style: "solid" }) };
27
- var LineItem = z.object({ ...base, ...stroked, type: z.literal("line"), a: Point, b: Point });
28
- var PolylineItem = z.object({
82
+ var LineItem = z2.object({ ...base, ...stroked, type: z2.literal("line"), a: Point, b: Point });
83
+ var PolylineItem = z2.object({
29
84
  ...base,
30
85
  ...stroked,
31
- type: z.literal("polyline"),
32
- points: z.array(Point).min(2),
33
- closed: z.boolean().default(false),
86
+ type: z2.literal("polyline"),
87
+ points: z2.array(Point).min(2),
88
+ closed: z2.boolean().default(false),
34
89
  fill: Fill.default("none")
35
90
  });
36
- var PathItem = z.object({ ...base, ...stroked, type: z.literal("path"), d: z.string().min(1), fill: Fill.default("none") });
37
- var RectItem = z.object({
91
+ var PathItem = z2.object({ ...base, ...stroked, type: z2.literal("path"), d: z2.string().min(1), fill: Fill.default("none") });
92
+ var RectItem = z2.object({
38
93
  ...base,
39
94
  ...stroked,
40
- type: z.literal("rect"),
41
- x: z.number(),
42
- y: z.number(),
43
- w: z.number().positive(),
44
- h: z.number().positive(),
45
- radius: z.number().min(0).default(0),
95
+ type: z2.literal("rect"),
96
+ x: z2.number(),
97
+ y: z2.number(),
98
+ w: z2.number().positive(),
99
+ h: z2.number().positive(),
100
+ radius: z2.number().min(0).default(0),
46
101
  fill: Fill.default("none")
47
102
  });
48
- var EllipseItem = z.object({
103
+ var EllipseItem = z2.object({
49
104
  ...base,
50
105
  ...stroked,
51
- type: z.literal("ellipse"),
52
- cx: z.number(),
53
- cy: z.number(),
54
- rx: z.number().positive(),
55
- ry: z.number().positive(),
106
+ type: z2.literal("ellipse"),
107
+ cx: z2.number(),
108
+ cy: z2.number(),
109
+ rx: z2.number().positive(),
110
+ ry: z2.number().positive(),
56
111
  fill: Fill.default("none")
57
112
  });
58
- var ArcItem = z.object({
113
+ var ArcItem = z2.object({
59
114
  ...base,
60
115
  ...stroked,
61
- type: z.literal("arc"),
62
- cx: z.number(),
63
- cy: z.number(),
64
- r: z.number().positive(),
116
+ type: z2.literal("arc"),
117
+ cx: z2.number(),
118
+ cy: z2.number(),
119
+ r: z2.number().positive(),
65
120
  /** Degrees, 0 = +x axis, clockwise (SVG convention). */
66
- start: z.number(),
67
- end: z.number()
121
+ start: z2.number(),
122
+ end: z2.number()
68
123
  });
69
- var TextAnchor = z.enum(["start", "middle", "end"]);
70
- var TextItem = z.object({
124
+ var TextAnchor = z2.enum(["start", "middle", "end"]);
125
+ var TextItem = z2.object({
71
126
  ...base,
72
- type: z.literal("text"),
73
- x: z.number(),
74
- y: z.number(),
75
- text: z.string().min(1),
127
+ type: z2.literal("text"),
128
+ x: z2.number(),
129
+ y: z2.number(),
130
+ text: z2.string().min(1),
76
131
  /** Cap height in mm. */
77
- size: z.number().positive().default(3.5),
132
+ size: z2.number().positive().default(3.5),
78
133
  anchor: TextAnchor.default("start")
79
134
  });
80
- var NumeralItem = z.object({
135
+ var NumeralItem = z2.object({
81
136
  ...base,
82
- type: z.literal("numeral"),
137
+ type: z2.literal("numeral"),
83
138
  /** Numeral text, e.g. "102" or "102a". Looked up in Document.numerals. */
84
- n: z.string().regex(/^\d+[a-z']*$/i),
139
+ n: z2.string().regex(/^\d+[a-z']*$/i),
85
140
  at: Point,
86
141
  target: Point,
87
- leader: z.enum(["straight", "curved", "none"]).default("curved"),
142
+ leader: z2.enum(["straight", "curved", "none"]).default("curved"),
88
143
  /** When true, numeral is underlined (refers to the whole assembly). */
89
- underline: z.boolean().default(false),
90
- size: z.number().positive().default(3.5)
144
+ underline: z2.boolean().default(false),
145
+ size: z2.number().positive().default(3.5)
91
146
  });
92
- var FigLabelItem = z.object({
147
+ var FigLabelItem = z2.object({
93
148
  ...base,
94
- type: z.literal("figLabel"),
95
- x: z.number(),
96
- y: z.number(),
97
- size: z.number().positive().default(5)
149
+ type: z2.literal("figLabel"),
150
+ x: z2.number(),
151
+ y: z2.number(),
152
+ size: z2.number().positive().default(5)
98
153
  });
99
- var Side = z.enum(["top", "bottom", "left", "right"]);
100
- var ConnectorEnd = z.union([
101
- z.object({ itemId: z.string() }),
102
- z.object({ point: Point })
154
+ var Side = z2.enum(["top", "bottom", "left", "right"]);
155
+ var ConnectorEnd = z2.union([
156
+ z2.object({ itemId: z2.string() }),
157
+ z2.object({ point: Point })
103
158
  ]);
104
- var ConnectorItem = z.object({
159
+ var ConnectorItem = z2.object({
105
160
  ...base,
106
161
  ...stroked,
107
- type: z.literal("connector"),
162
+ type: z2.literal("connector"),
108
163
  from: ConnectorEnd,
109
164
  to: ConnectorEnd,
110
- routing: z.enum(["straight", "orthogonal", "curved"]).default("orthogonal"),
165
+ routing: z2.enum(["straight", "orthogonal", "curved"]).default("orthogonal"),
111
166
  /** Which side of an attached item the connector leaves/enters; auto when omitted. */
112
167
  fromSide: Side.optional(),
113
168
  toSide: Side.optional(),
114
- arrow: z.enum(["none", "end", "start", "both"]).default("end"),
115
- arrowStyle: z.enum(["filled", "open"]).default("filled"),
116
- label: z.string().optional()
169
+ arrow: z2.enum(["none", "end", "start", "both"]).default("end"),
170
+ arrowStyle: z2.enum(["filled", "open"]).default("filled"),
171
+ label: z2.string().optional()
117
172
  });
118
- var HatchItem = z.object({
173
+ var HatchItem = z2.object({
119
174
  ...base,
120
- type: z.literal("hatch"),
121
- points: z.array(Point).min(3),
122
- angle: z.number().default(45),
123
- spacing: z.number().positive().default(1.5),
124
- lineWidth: z.number().positive().default(0.25)
175
+ type: z2.literal("hatch"),
176
+ points: z2.array(Point).min(3),
177
+ angle: z2.number().default(45),
178
+ spacing: z2.number().positive().default(1.5),
179
+ lineWidth: z2.number().positive().default(0.25)
125
180
  });
126
- var SectionLineItem = z.object({
181
+ var SectionLineItem = z2.object({
127
182
  ...base,
128
183
  ...stroked,
129
- type: z.literal("sectionLine"),
184
+ type: z2.literal("sectionLine"),
130
185
  a: Point,
131
186
  b: Point,
132
- label: z.string().min(1).max(3)
187
+ label: z2.string().min(1).max(3)
133
188
  });
134
- var Item = z.discriminatedUnion("type", [
189
+ var Item = z2.discriminatedUnion("type", [
135
190
  LineItem,
136
191
  PolylineItem,
137
192
  PathItem,
@@ -145,45 +200,72 @@ var Item = z.discriminatedUnion("type", [
145
200
  HatchItem,
146
201
  SectionLineItem
147
202
  ]);
148
- var Offset = z.object({ dx: z.number(), dy: z.number() });
149
- var Layer = z.object({
150
- id: z.string().min(1),
151
- name: z.string().min(1),
152
- visible: z.boolean().default(true),
153
- locked: z.boolean().default(false),
203
+ var Offset = z2.object({ dx: z2.number(), dy: z2.number() });
204
+ var Layer = z2.object({
205
+ id: z2.string().min(1),
206
+ name: z2.string().min(1),
207
+ visible: z2.boolean().default(true),
208
+ locked: z2.boolean().default(false),
154
209
  /** Where this component moves to in the exploded view (mm). */
155
210
  explode: Offset.optional(),
156
- items: z.array(Item).default([])
211
+ items: z2.array(Item).default([])
157
212
  });
158
- var JurisdictionId = z.enum(["uspto", "pct", "epo", "ipo"]);
159
- var SheetSize = z.enum(["a4", "letter"]);
160
- var Sheet = z.object({
213
+ var JurisdictionId = z2.enum(["uspto", "pct", "epo", "ipo"]);
214
+ var SheetSize = z2.enum(["a4", "letter"]);
215
+ var Sheet = z2.object({
161
216
  size: SheetSize.default("a4"),
162
- orientation: z.enum(["portrait", "landscape"]).default("portrait")
217
+ orientation: z2.enum(["portrait", "landscape"]).default("portrait")
218
+ });
219
+ var LetteringStyle = z2.object({
220
+ numeralWeight: z2.enum(["regular", "bold"]).default("regular"),
221
+ figLabel: z2.enum(["sans-bold", "serif-italic"]).default("sans-bold")
163
222
  });
164
- var LetteringStyle = z.object({
165
- numeralWeight: z.enum(["regular", "bold"]).default("regular"),
166
- figLabel: z.enum(["sans-bold", "serif-italic"]).default("sans-bold")
223
+ var NumeralRegistry = z2.record(z2.string(), z2.string());
224
+ var ChatTranscript = z2.array(z2.unknown());
225
+ var DrawingSnapshot = z2.object({
226
+ jurisdiction: JurisdictionId,
227
+ sheet: Sheet,
228
+ layers: z2.array(Layer),
229
+ numerals: NumeralRegistry,
230
+ lettering: LetteringStyle,
231
+ view: z2.enum(["composite", "exploded"]),
232
+ explodeLines: z2.boolean(),
233
+ sheetLabel: z2.string().max(12).optional()
167
234
  });
168
- var NumeralRegistry = z.record(z.string(), z.string());
169
- var ChatTranscript = z.array(z.unknown());
170
- var PatentDocument = z.object({
171
- version: z.literal(1).default(1),
172
- id: z.string().min(1),
173
- figureNumber: z.string().min(1),
235
+ var RunRecord = z2.object({
236
+ id: z2.string().min(1),
237
+ /** "new" draws the figure, "edit" changes one that already had content. */
238
+ kind: z2.enum(["new", "edit"]),
239
+ request: z2.string(),
240
+ preferences: GenerationPrefs.optional(),
241
+ selection: z2.array(z2.string()).default([]),
242
+ /** Transcript length before the request, so a retry can replace the turn. */
243
+ chatLength: z2.number().int().nonnegative().default(0),
244
+ plan: FigurePlan.optional(),
245
+ steps: z2.array(z2.object({ label: z2.string(), status: z2.enum(["done", "active"]) })).default([]),
246
+ /** Number of individual changes the run made. */
247
+ edits: z2.number().int().nonnegative().default(0),
248
+ before: DrawingSnapshot
249
+ });
250
+ var PatentDocument = z2.object({
251
+ version: z2.literal(1).default(1),
252
+ id: z2.string().min(1),
253
+ figureNumber: z2.string().min(1),
174
254
  /** Patent office whose drawing rules apply. Defaults to India (IPO). */
175
255
  jurisdiction: JurisdictionId.default("ipo"),
176
256
  sheet: Sheet.default({ size: "a4", orientation: "portrait" }),
177
- layers: z.array(Layer).default([]),
257
+ layers: z2.array(Layer).default([]),
178
258
  numerals: NumeralRegistry.default({}),
179
259
  lettering: LetteringStyle.default({ numeralWeight: "regular", figLabel: "sans-bold" }),
180
260
  /** Which view of the same model is shown and exported. */
181
- view: z.enum(["composite", "exploded"]).default("composite"),
261
+ view: z2.enum(["composite", "exploded"]).default("composite"),
182
262
  /** Exploded view: dash-dot alignment lines between separated components. */
183
- explodeLines: z.boolean().default(true),
263
+ explodeLines: z2.boolean().default(true),
184
264
  /** Sheet number shown top-centre inside the sight, e.g. "1/3" (37 CFR 1.84(t)). Set by the host. */
185
- sheetLabel: z.string().max(12).optional(),
186
- chat: ChatTranscript.default([])
265
+ sheetLabel: z2.string().max(12).optional(),
266
+ chat: ChatTranscript.default([]),
267
+ /** Unfinished assistant run. A record that can't be read is dropped, never a load error. */
268
+ run: RunRecord.optional().catch(void 0)
187
269
  });
188
270
  function normalizeDocument(input) {
189
271
  const r = PatentDocument.safeParse(input);
@@ -210,25 +292,25 @@ function createDocument(init) {
210
292
  import { createContext, useCallback, useContext, useMemo, useReducer } from "react";
211
293
 
212
294
  // ../../src/patent-render/schema/patch.ts
213
- import { z as z2 } from "zod";
214
- var ItemChanges = z2.record(z2.string(), z2.unknown());
295
+ import { z as z3 } from "zod";
296
+ var ItemChanges = z3.record(z3.string(), z3.unknown());
215
297
  var LayerChanges = Layer.omit({ id: true, items: true }).partial();
216
- var Patch = z2.discriminatedUnion("op", [
217
- z2.object({ op: z2.literal("addLayer"), layer: Layer, index: z2.number().int().optional() }),
218
- z2.object({ op: z2.literal("updateLayer"), id: z2.string(), changes: LayerChanges }),
219
- z2.object({ op: z2.literal("removeLayer"), id: z2.string() }),
220
- z2.object({ op: z2.literal("moveLayer"), id: z2.string(), toIndex: z2.number().int() }),
221
- z2.object({ op: z2.literal("addItem"), layerId: z2.string(), item: Item, index: z2.number().int().optional() }),
222
- z2.object({ op: z2.literal("updateItem"), id: z2.string(), changes: ItemChanges }),
223
- z2.object({ op: z2.literal("removeItem"), id: z2.string() }),
224
- z2.object({ op: z2.literal("moveItem"), id: z2.string(), toLayerId: z2.string(), toIndex: z2.number().int().optional() }),
225
- z2.object({ op: z2.literal("setNumeral"), n: z2.string(), label: z2.string().nullable() }),
226
- z2.object({ op: z2.literal("setSheet"), sheet: Sheet }),
227
- z2.object({ op: z2.literal("setJurisdiction"), jurisdiction: JurisdictionId }),
228
- z2.object({ op: z2.literal("setLettering"), lettering: LetteringStyle }),
229
- z2.object({ op: z2.literal("setView"), view: z2.enum(["composite", "exploded"]), explodeLines: z2.boolean().optional() }),
230
- z2.object({ op: z2.literal("setSheetLabel"), sheetLabel: z2.string().max(12).nullable() }),
231
- z2.object({ op: z2.literal("batch"), patches: z2.array(z2.lazy(() => Patch)) })
298
+ var Patch = z3.discriminatedUnion("op", [
299
+ z3.object({ op: z3.literal("addLayer"), layer: Layer, index: z3.number().int().optional() }),
300
+ z3.object({ op: z3.literal("updateLayer"), id: z3.string(), changes: LayerChanges }),
301
+ z3.object({ op: z3.literal("removeLayer"), id: z3.string() }),
302
+ z3.object({ op: z3.literal("moveLayer"), id: z3.string(), toIndex: z3.number().int() }),
303
+ z3.object({ op: z3.literal("addItem"), layerId: z3.string(), item: Item, index: z3.number().int().optional() }),
304
+ z3.object({ op: z3.literal("updateItem"), id: z3.string(), changes: ItemChanges }),
305
+ z3.object({ op: z3.literal("removeItem"), id: z3.string() }),
306
+ z3.object({ op: z3.literal("moveItem"), id: z3.string(), toLayerId: z3.string(), toIndex: z3.number().int().optional() }),
307
+ z3.object({ op: z3.literal("setNumeral"), n: z3.string(), label: z3.string().nullable() }),
308
+ z3.object({ op: z3.literal("setSheet"), sheet: Sheet }),
309
+ z3.object({ op: z3.literal("setJurisdiction"), jurisdiction: JurisdictionId }),
310
+ z3.object({ op: z3.literal("setLettering"), lettering: LetteringStyle }),
311
+ z3.object({ op: z3.literal("setView"), view: z3.enum(["composite", "exploded"]), explodeLines: z3.boolean().optional() }),
312
+ z3.object({ op: z3.literal("setSheetLabel"), sheetLabel: z3.string().max(12).nullable() }),
313
+ z3.object({ op: z3.literal("batch"), patches: z3.array(z3.lazy(() => Patch)) })
232
314
  ]);
233
315
  var PatchError = class extends Error {
234
316
  };
@@ -1241,7 +1323,7 @@ function useEditor() {
1241
1323
  }
1242
1324
 
1243
1325
  // ../../src/patent-render/client/PatentRenderEditor.tsx
1244
- import { useEffect as useEffect4, useRef as useRef4, useState as useState8 } from "react";
1326
+ import { useEffect as useEffect4, useRef as useRef5, useState as useState8 } from "react";
1245
1327
  import { cn as cn25 } from "cn";
1246
1328
 
1247
1329
  // ../../src/patent-render/render/nodes.ts
@@ -1658,7 +1740,7 @@ function isItemEditable(doc, id) {
1658
1740
  }
1659
1741
 
1660
1742
  // ../../src/patent-render/client/Canvas.tsx
1661
- import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo as useMemo3, useRef, useState as useState2 } from "react";
1743
+ import { useCallback as useCallback2, useEffect, useLayoutEffect as useLayoutEffect2, useMemo as useMemo3, useRef as useRef2, useState as useState2 } from "react";
1662
1744
  import { Loader2 } from "lucide-react";
1663
1745
  import { cn as cn6 } from "cn";
1664
1746
 
@@ -1879,7 +1961,7 @@ function ZoomControls({
1879
1961
  }
1880
1962
 
1881
1963
  // ../../src/patent-render/client/pathTools.tsx
1882
- import { useState } from "react";
1964
+ import { useLayoutEffect, useRef, useState } from "react";
1883
1965
 
1884
1966
  // ../../src/patent-render/geometry/bezier.ts
1885
1967
  var r32 = (n) => Math.round(n * 1e3) / 1e3;
@@ -2060,16 +2142,30 @@ function insertNode(subs, p, maxDist) {
2060
2142
  return { subs: out, ref: { s: b.s, n: b.i + 1 } };
2061
2143
  }
2062
2144
  function usePathTools({ doc, tool, zoom, addItem, apply }) {
2063
- const [pen, setPen] = useState(null);
2064
- const [edit, setEdit] = useState(null);
2145
+ const [pen, setPenState] = useState(null);
2146
+ const [edit, setEditState] = useState(null);
2147
+ const penRef = useRef(null);
2148
+ const editRef = useRef(null);
2149
+ const setPen = (p) => {
2150
+ penRef.current = p;
2151
+ setPenState(p);
2152
+ };
2153
+ const setEdit = (e) => {
2154
+ editRef.current = e;
2155
+ setEditState(e);
2156
+ };
2157
+ useLayoutEffect(() => {
2158
+ penRef.current = pen;
2159
+ editRef.current = edit;
2160
+ });
2065
2161
  const [lastTool, setLastTool] = useState(tool);
2066
2162
  if (tool !== lastTool) {
2067
2163
  setLastTool(tool);
2068
- setPen(null);
2069
- if (tool !== "select") setEdit(null);
2164
+ setPenState(null);
2165
+ if (tool !== "select") setEditState(null);
2070
2166
  }
2071
2167
  const px = (n) => n / zoom;
2072
- const finishPen = (closed, state = pen) => {
2168
+ const finishPen = (closed, state = penRef.current) => {
2073
2169
  if (!state) return;
2074
2170
  const nodes = state.nodes;
2075
2171
  const base3 = { rotation: 0, locked: false, hidden: false };
@@ -2113,22 +2209,23 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2113
2209
  }
2114
2210
  };
2115
2211
  const onPointerDown = (target, p, altKey) => {
2212
+ const pen2 = penRef.current, edit2 = editRef.current;
2116
2213
  if (tool === "polyline" || tool === "hatch") {
2117
- if (pen && nearFirst(p, pen)) {
2214
+ if (pen2 && nearFirst(p, pen2)) {
2118
2215
  finishPen(true);
2119
2216
  return true;
2120
2217
  }
2121
- const nodes = [...pen?.nodes ?? [], { p }];
2218
+ const nodes = [...pen2?.nodes ?? [], { p }];
2122
2219
  setPen({ tool, nodes, cur: p, dragging: tool === "polyline" ? nodes.length - 1 : null });
2123
2220
  return true;
2124
2221
  }
2125
- if (!edit) return false;
2222
+ if (!edit2) return false;
2126
2223
  const tag = target.getAttribute?.("data-node");
2127
2224
  if (tag) {
2128
2225
  const [kind, s, n] = tag.split(":");
2129
2226
  const ref = { s: Number(s), n: Number(n) };
2130
2227
  if (kind === "anchor" && altKey) {
2131
- const subs = clone(edit.subs);
2228
+ const subs = clone(edit2.subs);
2132
2229
  const sp = subs[ref.s], node = sp.nodes[ref.n];
2133
2230
  if (node.in || node.out) {
2134
2231
  delete node.in;
@@ -2139,33 +2236,34 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2139
2236
  node.in = [node.p[0] - dx, node.p[1] - dy];
2140
2237
  node.out = [node.p[0] + dx, node.p[1] + dy];
2141
2238
  }
2142
- const next = { ...edit, subs, sel: ref };
2239
+ const next = { ...edit2, subs, sel: ref };
2143
2240
  setEdit(next);
2144
2241
  commit(next);
2145
2242
  return true;
2146
2243
  }
2147
- setEdit({ ...edit, sel: ref, drag: { kind, ref, start: p, orig: clone(edit.subs), alt: altKey } });
2244
+ setEdit({ ...edit2, sel: ref, drag: { kind, ref, start: p, orig: clone(edit2.subs), alt: altKey } });
2148
2245
  return true;
2149
2246
  }
2150
- if (target.closest?.(`[data-hit-id="${edit.id}"]`)) {
2151
- setEdit({ ...edit, sel: null });
2247
+ if (target.closest?.(`[data-hit-id="${edit2.id}"]`)) {
2248
+ setEdit({ ...edit2, sel: null });
2152
2249
  return true;
2153
2250
  }
2154
2251
  setEdit(null);
2155
2252
  return false;
2156
2253
  };
2157
2254
  const onPointerMove = (p, altKey) => {
2158
- if (pen) {
2159
- if (pen.dragging !== null) {
2160
- const nodes = pen.nodes.slice();
2161
- const a = nodes[pen.dragging];
2162
- if (dist(p, a.p) > px(3)) nodes[pen.dragging] = { p: a.p, out: p, in: [2 * a.p[0] - p[0], 2 * a.p[1] - p[1]] };
2163
- setPen({ ...pen, nodes, cur: p });
2164
- } else setPen({ ...pen, cur: p });
2255
+ const pen2 = penRef.current, edit2 = editRef.current;
2256
+ if (pen2) {
2257
+ if (pen2.dragging !== null) {
2258
+ const nodes = pen2.nodes.slice();
2259
+ const a = nodes[pen2.dragging];
2260
+ if (dist(p, a.p) > px(3)) nodes[pen2.dragging] = { p: a.p, out: p, in: [2 * a.p[0] - p[0], 2 * a.p[1] - p[1]] };
2261
+ setPen({ ...pen2, nodes, cur: p });
2262
+ } else setPen({ ...pen2, cur: p });
2165
2263
  return;
2166
2264
  }
2167
- if (!edit?.drag) return;
2168
- const { kind, ref, start, orig } = edit.drag;
2265
+ if (!edit2?.drag) return;
2266
+ const { kind, ref, start, orig } = edit2.drag;
2169
2267
  const subs = clone(orig);
2170
2268
  const node = subs[ref.s].nodes[ref.n];
2171
2269
  const d = [p[0] - start[0], p[1] - start[1]];
@@ -2176,33 +2274,35 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2176
2274
  } else {
2177
2275
  const other = kind === "in" ? "out" : "in";
2178
2276
  node[kind] = p;
2179
- if (node[other] && !altKey && !edit.drag.alt) node[other] = mirrorHandle(node.p, p, node[other]);
2277
+ if (node[other] && !altKey && !edit2.drag.alt) node[other] = mirrorHandle(node.p, p, node[other]);
2180
2278
  }
2181
- setEdit({ ...edit, subs, dirty: true });
2279
+ setEdit({ ...edit2, subs, dirty: true });
2182
2280
  };
2183
2281
  const onPointerUp = () => {
2184
- if (pen && pen.dragging !== null) {
2185
- setPen({ ...pen, dragging: null });
2282
+ const pen2 = penRef.current, edit2 = editRef.current;
2283
+ if (pen2 && pen2.dragging !== null) {
2284
+ setPen({ ...pen2, dragging: null });
2186
2285
  return true;
2187
2286
  }
2188
- if (edit?.drag) {
2189
- const done = { ...edit, drag: null, dirty: false };
2190
- if (edit.dirty) commit(edit);
2287
+ if (edit2?.drag) {
2288
+ const done = { ...edit2, drag: null, dirty: false };
2289
+ if (edit2.dirty) commit(edit2);
2191
2290
  setEdit(done);
2192
2291
  return true;
2193
2292
  }
2194
2293
  return false;
2195
2294
  };
2196
2295
  const onDoubleClick = (p, hitId) => {
2197
- if (pen) {
2198
- const nodes = pen.nodes.length > 1 && dist(pen.nodes[pen.nodes.length - 1].p, pen.nodes[pen.nodes.length - 2].p) < px(4) ? pen.nodes.slice(0, -1) : pen.nodes;
2199
- finishPen(false, { ...pen, nodes });
2296
+ const pen2 = penRef.current, edit2 = editRef.current;
2297
+ if (pen2) {
2298
+ const nodes = pen2.nodes.length > 1 && dist(pen2.nodes[pen2.nodes.length - 1].p, pen2.nodes[pen2.nodes.length - 2].p) < px(4) ? pen2.nodes.slice(0, -1) : pen2.nodes;
2299
+ finishPen(false, { ...pen2, nodes });
2200
2300
  return true;
2201
2301
  }
2202
- if (edit) {
2203
- const r = insertNode(edit.subs, p, px(8));
2302
+ if (edit2) {
2303
+ const r = insertNode(edit2.subs, p, px(8));
2204
2304
  if (r) {
2205
- const next = { ...edit, subs: r.subs, sel: r.ref };
2305
+ const next = { ...edit2, subs: r.subs, sel: r.ref };
2206
2306
  setEdit(next);
2207
2307
  commit(next);
2208
2308
  }
@@ -2508,6 +2608,16 @@ import { Fragment, jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
2508
2608
  var HANDLES = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
2509
2609
  var DRAW_TOOLS = ["line", "rect", "ellipse", "sectionLine", "shape"];
2510
2610
  var HIT_PX = 7;
2611
+ var WHEEL_LINE_PX = 16;
2612
+ var WHEEL_ZOOM_MAX = Math.log(1.25);
2613
+ var WHEEL_ZOOM_PER_PX = 0.01;
2614
+ var WHEEL_NOTCH_PX = 40;
2615
+ var PAN_EASE = 0.35;
2616
+ var INTERIOR_GRAB_MAX_PX = 200;
2617
+ function wheelPx(e, pageHeight) {
2618
+ const k = e.deltaMode === 1 ? WHEEL_LINE_PX : e.deltaMode === 2 ? pageHeight : 1;
2619
+ return [e.deltaX * k, e.deltaY * k];
2620
+ }
2511
2621
  function hitify(n, w) {
2512
2622
  const attrs = {};
2513
2623
  for (const [k, v] of Object.entries(n.attrs)) {
@@ -2520,6 +2630,7 @@ function hitify(n, w) {
2520
2630
  } else if (n.tag !== "g" && n.tag !== "clipPath") {
2521
2631
  attrs.stroke = "transparent";
2522
2632
  attrs["stroke-width"] = w;
2633
+ attrs["vector-effect"] = "non-scaling-stroke";
2523
2634
  attrs["pointer-events"] = attrs.fill && attrs.fill !== "none" ? "all" : "stroke";
2524
2635
  if (attrs.fill && attrs.fill !== "none") attrs.fill = "transparent";
2525
2636
  }
@@ -2544,59 +2655,138 @@ var CURSOR = {
2544
2655
  };
2545
2656
  function Canvas({ className }) {
2546
2657
  const ed = useEditor();
2547
- const { doc, selection, tool, view, snap } = ed.state;
2548
- const wrapRef = useRef(null);
2549
- const svgRef = useRef(null);
2658
+ const { doc, selection, tool, snap } = ed.state;
2659
+ const wrapRef = useRef2(null);
2660
+ const svgRef = useRef2(null);
2550
2661
  const [size, setSize] = useState2({ w: 0, h: 0 });
2551
- const [gesture, setGesture] = useState2(null);
2662
+ const [gesture, setGestureState] = useState2(null);
2663
+ const gestureRef = useRef2(null);
2664
+ const setGesture = useCallback2((g) => {
2665
+ gestureRef.current = g;
2666
+ setGestureState(g);
2667
+ }, []);
2552
2668
  const [inline, setInline] = useState2(null);
2553
2669
  const [spaceDown, setSpaceDown] = useState2(false);
2554
2670
  const [portHover, setPortHover] = useState2(null);
2555
2671
  const sheet = sheetDims(doc.sheet);
2556
2672
  const exploded = doc.view === "exploded" && hasExplode(doc);
2673
+ const [view, setViewState] = useState2(ed.state.view);
2674
+ const viewRef = useRef2(ed.state.view);
2675
+ const viewFrame = useRef2(null);
2676
+ const setView = useCallback2((next, immediate = false) => {
2677
+ viewRef.current = next;
2678
+ if (immediate) {
2679
+ if (viewFrame.current !== null) {
2680
+ cancelAnimationFrame(viewFrame.current);
2681
+ viewFrame.current = null;
2682
+ }
2683
+ setViewState(next);
2684
+ return;
2685
+ }
2686
+ if (viewFrame.current === null) {
2687
+ viewFrame.current = requestAnimationFrame(() => {
2688
+ viewFrame.current = null;
2689
+ setViewState(viewRef.current);
2690
+ });
2691
+ }
2692
+ }, []);
2693
+ useEffect(() => () => {
2694
+ if (viewFrame.current !== null) cancelAnimationFrame(viewFrame.current);
2695
+ }, []);
2696
+ const syncedView = useRef2(ed.state.view);
2697
+ useEffect(() => {
2698
+ if (!view || view === syncedView.current) return;
2699
+ const t = setTimeout(() => {
2700
+ syncedView.current = view;
2701
+ ed.setView(view);
2702
+ }, 250);
2703
+ return () => clearTimeout(t);
2704
+ }, [view]);
2705
+ useEffect(() => {
2706
+ const ext = ed.state.view;
2707
+ if (ext && ext !== syncedView.current && ext !== viewRef.current) {
2708
+ syncedView.current = ext;
2709
+ setView(ext, true);
2710
+ }
2711
+ }, [ed.state.view, setView]);
2557
2712
  const fit = useCallback2(() => {
2558
2713
  if (!size.w || !size.h) return;
2559
2714
  const zoom = Math.min(size.w / sheet.w, size.h / sheet.h) * 0.9;
2560
- ed.setView({ zoom, panX: (size.w - sheet.w * zoom) / 2, panY: (size.h - sheet.h * zoom) / 2 });
2561
- }, [size.w, size.h, sheet.w, sheet.h, ed]);
2562
- useLayoutEffect(() => {
2715
+ setView({ zoom, panX: (size.w - sheet.w * zoom) / 2, panY: (size.h - sheet.h * zoom) / 2 }, true);
2716
+ }, [size.w, size.h, sheet.w, sheet.h, setView]);
2717
+ useLayoutEffect2(() => {
2563
2718
  const el = wrapRef.current;
2564
2719
  if (!el) return;
2565
2720
  const ro = new ResizeObserver(([e]) => setSize({ w: e.contentRect.width, h: e.contentRect.height }));
2566
2721
  ro.observe(el);
2567
2722
  return () => ro.disconnect();
2568
2723
  }, []);
2569
- const userMoved = useRef(false);
2724
+ const userMoved = useRef2(false);
2725
+ const fitPending = useRef2(false);
2570
2726
  useEffect(() => {
2571
- if (size.w && (!view || !userMoved.current)) fit();
2727
+ if (!size.w || viewRef.current && userMoved.current) return;
2728
+ if (gestureRef.current) {
2729
+ fitPending.current = true;
2730
+ return;
2731
+ }
2732
+ fit();
2572
2733
  }, [size.w, size.h]);
2573
2734
  const v = view ?? { zoom: 1, panX: 0, panY: 0 };
2574
2735
  const zoomAt = useCallback2((factor, sx, sy) => {
2575
- const cur = ed.state.view;
2736
+ const cur = viewRef.current;
2576
2737
  if (!cur) return;
2577
2738
  userMoved.current = true;
2578
2739
  const zoom = Math.min(40, Math.max(0.3, cur.zoom * factor));
2579
2740
  const k = zoom / cur.zoom;
2580
- ed.setView({ zoom, panX: sx - (sx - cur.panX) * k, panY: sy - (sy - cur.panY) * k });
2581
- }, [ed]);
2741
+ setView({ zoom, panX: sx - (sx - cur.panX) * k, panY: sy - (sy - cur.panY) * k });
2742
+ }, [setView]);
2743
+ const panDebt = useRef2([0, 0]);
2744
+ const panFrame = useRef2(null);
2582
2745
  useEffect(() => {
2583
2746
  const el = svgRef.current;
2584
2747
  if (!el) return;
2748
+ function easePan() {
2749
+ panFrame.current = null;
2750
+ const cur = viewRef.current;
2751
+ if (!cur) {
2752
+ panDebt.current = [0, 0];
2753
+ return;
2754
+ }
2755
+ const [dx, dy] = panDebt.current;
2756
+ const done = Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5;
2757
+ const sx = done ? dx : dx * PAN_EASE, sy = done ? dy : dy * PAN_EASE;
2758
+ panDebt.current = [dx - sx, dy - sy];
2759
+ setView({ ...cur, panX: cur.panX - sx, panY: cur.panY - sy });
2760
+ if (!done) panFrame.current = requestAnimationFrame(easePan);
2761
+ }
2585
2762
  const onWheel = (e) => {
2586
2763
  e.preventDefault();
2587
- const cur = ed.state.view;
2764
+ const cur = viewRef.current;
2588
2765
  if (!cur) return;
2589
- const r = el.getBoundingClientRect();
2766
+ const [dx, dy] = wheelPx(e, el.clientHeight || 800);
2590
2767
  if (e.ctrlKey || e.metaKey) {
2591
- zoomAt(Math.exp(-e.deltaY * 0.01), e.clientX - r.left, e.clientY - r.top);
2768
+ const step = Math.max(-WHEEL_ZOOM_MAX, Math.min(WHEEL_ZOOM_MAX, -dy * WHEEL_ZOOM_PER_PX));
2769
+ const r = el.getBoundingClientRect();
2770
+ zoomAt(Math.exp(step), e.clientX - r.left, e.clientY - r.top);
2771
+ return;
2772
+ }
2773
+ userMoved.current = true;
2774
+ if (Math.abs(dx) >= WHEEL_NOTCH_PX || Math.abs(dy) >= WHEEL_NOTCH_PX) {
2775
+ panDebt.current = [panDebt.current[0] + dx, panDebt.current[1] + dy];
2776
+ if (panFrame.current === null) panFrame.current = requestAnimationFrame(easePan);
2592
2777
  } else {
2593
- userMoved.current = true;
2594
- ed.setView({ ...cur, panX: cur.panX - e.deltaX, panY: cur.panY - e.deltaY });
2778
+ setView({ ...cur, panX: cur.panX - dx, panY: cur.panY - dy });
2595
2779
  }
2596
2780
  };
2597
2781
  el.addEventListener("wheel", onWheel, { passive: false });
2598
- return () => el.removeEventListener("wheel", onWheel);
2599
- }, [ed, zoomAt]);
2782
+ return () => {
2783
+ el.removeEventListener("wheel", onWheel);
2784
+ if (panFrame.current !== null) {
2785
+ cancelAnimationFrame(panFrame.current);
2786
+ panFrame.current = null;
2787
+ }
2788
+ };
2789
+ }, [zoomAt, setView]);
2600
2790
  const addItem = (item) => {
2601
2791
  const layer = targetLayer(doc, ed.state.activeLayerId);
2602
2792
  if (!layer) return;
@@ -2643,7 +2833,8 @@ function Canvas({ className }) {
2643
2833
  });
2644
2834
  const toMm = (e) => {
2645
2835
  const r = svgRef.current.getBoundingClientRect();
2646
- return [(e.clientX - r.left - v.panX) / v.zoom, (e.clientY - r.top - v.panY) / v.zoom];
2836
+ const cv = viewRef.current ?? v;
2837
+ return [(e.clientX - r.left - cv.panX) / cv.zoom, (e.clientY - r.top - cv.panY) / cv.zoom];
2647
2838
  };
2648
2839
  const snapPt = (p) => snap ? [Math.round(p[0] * 2) / 2, Math.round(p[1] * 2) / 2] : p;
2649
2840
  const px = (n) => n / v.zoom;
@@ -2698,12 +2889,30 @@ function Canvas({ className }) {
2698
2889
  const el = e.target.closest?.("[data-hit-id]");
2699
2890
  return el ? el.getAttribute("data-hit-id") : null;
2700
2891
  };
2892
+ const interiorHit = (p) => {
2893
+ const z5 = (viewRef.current ?? v).zoom;
2894
+ let best = null;
2895
+ for (const l of vdoc.layers) {
2896
+ if (!l.visible || l.locked) continue;
2897
+ for (const it of l.items) {
2898
+ const closed = it.type === "rect" || it.type === "ellipse" || it.type === "polyline" && it.closed || it.type === "path" && /z\s*$/i.test(it.d);
2899
+ if (!closed || it.hidden || it.locked || !isItemEditable(doc, it.id)) continue;
2900
+ const b = itemBoundsRotated(vdoc, it);
2901
+ if (b.w * z5 > INTERIOR_GRAB_MAX_PX || b.h * z5 > INTERIOR_GRAB_MAX_PX) continue;
2902
+ if (p[0] < b.x || p[0] > b.x + b.w || p[1] < b.y || p[1] > b.y + b.h) continue;
2903
+ const area = b.w * b.h;
2904
+ if (!best || area < best.area) best = { id: it.id, area };
2905
+ }
2906
+ }
2907
+ return best?.id ?? null;
2908
+ };
2701
2909
  const onPointerDown = (e) => {
2702
2910
  if (e.button !== 0 && e.button !== 1) return;
2703
2911
  svgRef.current?.setPointerCapture(e.pointerId);
2704
2912
  const p = toMm(e);
2705
2913
  if (e.button === 1 || tool === "pan" || spaceDown) {
2706
- setGesture({ kind: "pan", sx: e.clientX, sy: e.clientY, px: v.panX, py: v.panY });
2914
+ const cv = viewRef.current ?? v;
2915
+ setGesture({ kind: "pan", sx: e.clientX, sy: e.clientY, px: cv.panX, py: cv.panY });
2707
2916
  return;
2708
2917
  }
2709
2918
  if (ed.readOnly) return;
@@ -2729,16 +2938,16 @@ function Canvas({ className }) {
2729
2938
  }
2730
2939
  return;
2731
2940
  }
2732
- const hit2 = hitItemId(e);
2941
+ const hit = hitItemId(e) ?? (tool === "select" && !e.shiftKey ? interiorHit(p) : null);
2733
2942
  if (tool === "select") {
2734
- if (hit2 && isItemEditable(doc, hit2)) {
2943
+ if (hit && isItemEditable(doc, hit)) {
2735
2944
  let ids = selection;
2736
- if (e.shiftKey) ids = selection.includes(hit2) ? selection.filter((i) => i !== hit2) : [...selection, hit2];
2737
- else if (!selection.includes(hit2)) ids = [hit2];
2945
+ if (e.shiftKey) ids = selection.includes(hit) ? selection.filter((i) => i !== hit) : [...selection, hit];
2946
+ else if (!selection.includes(hit)) ids = [hit];
2738
2947
  ed.select(ids);
2739
- const loc = findItem(doc, hit2);
2948
+ const loc = findItem(doc, hit);
2740
2949
  if (loc) ed.setActiveLayer(doc.layers[loc.layerIndex].id);
2741
- if (ids.includes(hit2)) setGesture({ kind: "move", start: p, ids: ids.filter((i) => isItemEditable(doc, i)), dx: 0, dy: 0 });
2950
+ if (ids.includes(hit)) setGesture({ kind: "move", start: p, ids: ids.filter((i) => isItemEditable(doc, i)), dx: 0, dy: 0 });
2742
2951
  } else {
2743
2952
  setGesture({ kind: "marquee", start: p, cur: p, base: e.shiftKey ? selection : [] });
2744
2953
  if (!e.shiftKey) ed.select([]);
@@ -2763,19 +2972,22 @@ function Canvas({ className }) {
2763
2972
  const onPointerMove = (e) => {
2764
2973
  const p = toMm(e);
2765
2974
  paths.onPointerMove(snapPt(p), e.altKey);
2766
- if (tool === "connector" && !gesture) {
2975
+ const gesture2 = gestureRef.current;
2976
+ if (tool === "connector" && !gesture2) {
2767
2977
  const over = attachTarget(p);
2768
2978
  const next = over ? { id: over, side: portAt(over, p) } : null;
2769
2979
  if (next?.id !== portHover?.id || next?.side !== portHover?.side) setPortHover(next);
2770
2980
  }
2771
- if (!gesture) return;
2772
- switch (gesture.kind) {
2773
- case "pan":
2981
+ if (!gesture2) return;
2982
+ switch (gesture2.kind) {
2983
+ case "pan": {
2774
2984
  userMoved.current = true;
2775
- ed.setView({ ...v, panX: gesture.px + e.clientX - gesture.sx, panY: gesture.py + e.clientY - gesture.sy });
2985
+ const cv = viewRef.current ?? v;
2986
+ setView({ ...cv, panX: gesture2.px + e.clientX - gesture2.sx, panY: gesture2.py + e.clientY - gesture2.sy });
2776
2987
  break;
2988
+ }
2777
2989
  case "move": {
2778
- let dx = p[0] - gesture.start[0], dy = p[1] - gesture.start[1];
2990
+ let dx = p[0] - gesture2.start[0], dy = p[1] - gesture2.start[1];
2779
2991
  if (e.shiftKey) {
2780
2992
  if (Math.abs(dx) > Math.abs(dy)) dy = 0;
2781
2993
  else dx = 0;
@@ -2784,11 +2996,11 @@ function Canvas({ className }) {
2784
2996
  dx = Math.round(dx * 2) / 2;
2785
2997
  dy = Math.round(dy * 2) / 2;
2786
2998
  }
2787
- setGesture({ ...gesture, dx, dy });
2999
+ setGesture({ ...gesture2, dx, dy });
2788
3000
  break;
2789
3001
  }
2790
3002
  case "resize": {
2791
- const { box, handle, origin } = gesture;
3003
+ const { box, handle, origin } = gesture2;
2792
3004
  const hp = handlePos(box, handle);
2793
3005
  const dxh = hp[0] - origin[0], dyh = hp[1] - origin[1];
2794
3006
  let sx = handle === "n" || handle === "s" || Math.abs(dxh) < 1e-6 ? 1 : (p[0] - origin[0]) / dxh;
@@ -2798,51 +3010,58 @@ function Canvas({ className }) {
2798
3010
  sx = Math.sign(sx) * s;
2799
3011
  sy = Math.sign(sy) * s;
2800
3012
  }
2801
- setGesture({ ...gesture, sx: sx || 0.01, sy: sy || 0.01 });
3013
+ setGesture({ ...gesture2, sx: sx || 0.01, sy: sy || 0.01 });
2802
3014
  break;
2803
3015
  }
2804
3016
  case "rotate": {
2805
- const a = Math.atan2(p[1] - gesture.c[1], p[0] - gesture.c[0]);
2806
- let rot = gesture.r0 + (a - gesture.a0) * 180 / Math.PI;
3017
+ const a = Math.atan2(p[1] - gesture2.c[1], p[0] - gesture2.c[0]);
3018
+ let rot = gesture2.r0 + (a - gesture2.a0) * 180 / Math.PI;
2807
3019
  if (e.shiftKey) rot = Math.round(rot / 15) * 15;
2808
3020
  rot = (rot % 360 + 360) % 360;
2809
- setGesture({ ...gesture, rot: Math.round(rot * 10) / 10 });
3021
+ setGesture({ ...gesture2, rot: Math.round(rot * 10) / 10 });
2810
3022
  break;
2811
3023
  }
2812
3024
  case "marquee":
2813
- setGesture({ ...gesture, cur: p });
3025
+ setGesture({ ...gesture2, cur: p });
2814
3026
  break;
2815
3027
  case "draw": {
2816
3028
  let cur = snapPt(p);
2817
- if ((gesture.tool === "line" || gesture.tool === "sectionLine") && e.shiftKey) cur = constrain45(gesture.start, cur);
2818
- setGesture({ ...gesture, cur });
3029
+ if ((gesture2.tool === "line" || gesture2.tool === "sectionLine") && e.shiftKey) cur = constrain45(gesture2.start, cur);
3030
+ setGesture({ ...gesture2, cur });
2819
3031
  break;
2820
3032
  }
2821
3033
  case "connector": {
2822
3034
  {
2823
3035
  const over = attachTarget(p);
2824
- const overId = over && !("itemId" in gesture.from && gesture.from.itemId === over) ? over : null;
2825
- setGesture({ ...gesture, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
3036
+ const overId = over && !("itemId" in gesture2.from && gesture2.from.itemId === over) ? over : null;
3037
+ setGesture({ ...gesture2, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2826
3038
  }
2827
3039
  break;
2828
3040
  }
2829
3041
  case "numeral":
2830
- setGesture({ ...gesture, cur: snapPt(p) });
3042
+ setGesture({ ...gesture2, cur: snapPt(p) });
2831
3043
  break;
2832
3044
  case "reconnect": {
2833
- const loc = findItem(doc, gesture.id);
2834
- const other = loc?.item.type === "connector" ? gesture.end === "from" ? loc.item.to : loc.item.from : null;
3045
+ const loc = findItem(doc, gesture2.id);
3046
+ const other = loc?.item.type === "connector" ? gesture2.end === "from" ? loc.item.to : loc.item.from : null;
2835
3047
  const over = attachTarget(p);
2836
3048
  const overId = over && !(other && "itemId" in other && other.itemId === over) ? over : null;
2837
- setGesture({ ...gesture, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
3049
+ setGesture({ ...gesture2, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2838
3050
  break;
2839
3051
  }
2840
3052
  }
2841
3053
  };
3054
+ const endGesture = () => {
3055
+ setGesture(null);
3056
+ if (fitPending.current) {
3057
+ fitPending.current = false;
3058
+ if (!userMoved.current) fit();
3059
+ }
3060
+ };
2842
3061
  const onPointerUp = () => {
2843
3062
  if (paths.onPointerUp()) return;
2844
- const g = gesture;
2845
- setGesture(null);
3063
+ const g = gestureRef.current;
3064
+ endGesture();
2846
3065
  if (!g) return;
2847
3066
  switch (g.kind) {
2848
3067
  case "move":
@@ -2918,16 +3137,16 @@ function Canvas({ className }) {
2918
3137
  const onDoubleClick = (e) => {
2919
3138
  if (ed.readOnly) return;
2920
3139
  const under = document.elementFromPoint(e.clientX, e.clientY);
2921
- const hit2 = under ? hitItemId({ target: under }) : null;
2922
- const editable = hit2 && isItemEditable(doc, hit2) ? hit2 : null;
3140
+ const hit = under ? hitItemId({ target: under }) : null;
3141
+ const editable = hit && isItemEditable(doc, hit) ? hit : null;
2923
3142
  if (paths.onDoubleClick(snapPt(toMm(e)), tool === "select" && !exploded ? editable : null)) return;
2924
- if (!hit2) return;
2925
- const loc = findItem(doc, hit2);
2926
- if (!loc || !isItemEditable(doc, hit2)) return;
3143
+ if (!hit) return;
3144
+ const loc = findItem(doc, hit);
3145
+ if (!loc || !isItemEditable(doc, hit)) return;
2927
3146
  const it = loc.item;
2928
- if (it.type === "text") setInline({ id: hit2, field: "text", value: it.text });
2929
- if (it.type === "numeral") setInline({ id: hit2, field: "desc", value: doc.numerals[it.n] ?? "", placeholder: `What is ${it.n}?` });
2930
- if (it.type === "connector") setInline({ id: hit2, field: "label", value: it.label ?? "" });
3147
+ if (it.type === "text") setInline({ id: hit, field: "text", value: it.text });
3148
+ if (it.type === "numeral") setInline({ id: hit, field: "desc", value: doc.numerals[it.n] ?? "", placeholder: `What is ${it.n}?` });
3149
+ if (it.type === "connector") setInline({ id: hit, field: "label", value: it.label ?? "" });
2931
3150
  };
2932
3151
  const refocusEditor = () => {
2933
3152
  const root = wrapRef.current?.closest("[data-slot=patent-render]");
@@ -2947,22 +3166,25 @@ function Canvas({ className }) {
2947
3166
  setInline(null);
2948
3167
  };
2949
3168
  const onContextMenu = (e) => {
2950
- const hit2 = hitItemId(e);
2951
- if (hit2 && !selection.includes(hit2) && isItemEditable(doc, hit2)) ed.select([hit2]);
2952
- if (!hit2) ed.select([]);
3169
+ const hit = hitItemId(e);
3170
+ if (hit && !selection.includes(hit) && isItemEditable(doc, hit)) ed.select([hit]);
3171
+ if (!hit) ed.select([]);
2953
3172
  };
2954
- const hitW = px(HIT_PX * 2);
2955
- const visual = useMemo3(() => layerNodes(vdoc), [vdoc]);
2956
- const hit = useMemo3(
3173
+ const defsEl = useMemo3(() => nodeToReact(defsNode(), "defs"), []);
3174
+ const drawingEls = useMemo3(() => [
3175
+ ...sheetLabelNodes(vdoc).map((n, i) => nodeToReact(n, `sheet-${i}`)),
3176
+ ...layerNodes(vdoc).map((n, i) => nodeToReact(n, n.attrs["data-layer-id"] ?? i))
3177
+ ], [vdoc]);
3178
+ const hitEls = useMemo3(
2957
3179
  () => vdoc.layers.filter((l) => l.visible).flatMap((l) => (
2958
3180
  // Locked layers/items are not hittable at all.
2959
3181
  l.locked ? [] : l.items.filter((it) => !it.hidden && !it.locked).map((it) => {
2960
- const n = hitify(itemNode(vdoc, it), hitW);
3182
+ const n = hitify(itemNode(vdoc, it), HIT_PX * 2);
2961
3183
  n.attrs["data-hit-id"] = it.id;
2962
- return n;
3184
+ return nodeToReact(n, it.id);
2963
3185
  })
2964
3186
  )),
2965
- [vdoc, hitW]
3187
+ [vdoc]
2966
3188
  );
2967
3189
  const profile = PROFILES[doc.jurisdiction];
2968
3190
  const m = effectiveMargins(profile, doc.sheet.orientation);
@@ -3005,11 +3227,11 @@ function Canvas({ className }) {
3005
3227
  onPointerDown,
3006
3228
  onPointerMove,
3007
3229
  onPointerUp,
3008
- onPointerCancel: () => setGesture(null),
3230
+ onPointerCancel: endGesture,
3009
3231
  onDoubleClick,
3010
3232
  onContextMenu,
3011
3233
  children: /* @__PURE__ */ jsxs6("g", { transform: `translate(${v.panX} ${v.panY}) scale(${v.zoom})`, children: [
3012
- nodeToReact(defsNode(), "defs"),
3234
+ defsEl,
3013
3235
  /* @__PURE__ */ jsx8("rect", { x: px(2), y: px(3), width: sheet.w, height: sheet.h, fill: "black", opacity: 0.08 }),
3014
3236
  /* @__PURE__ */ jsx8("rect", { x: 0, y: 0, width: sheet.w, height: sheet.h, fill: "#fff", stroke: "rgba(0,0,0,.15)", strokeWidth: px(1) }),
3015
3237
  /* @__PURE__ */ jsx8(
@@ -3026,11 +3248,8 @@ function Canvas({ className }) {
3026
3248
  pointerEvents: "none"
3027
3249
  }
3028
3250
  ),
3029
- /* @__PURE__ */ jsxs6("g", { pointerEvents: "none", children: [
3030
- sheetLabelNodes(vdoc).map((n, i) => nodeToReact(n, `sheet-${i}`)),
3031
- visual.map((n, i) => nodeToReact(n, n.attrs["data-layer-id"] ?? i))
3032
- ] }),
3033
- /* @__PURE__ */ jsx8("g", { children: hit.map((n) => nodeToReact(n, n.attrs["data-hit-id"])) }),
3251
+ /* @__PURE__ */ jsx8("g", { pointerEvents: "none", children: drawingEls }),
3252
+ /* @__PURE__ */ jsx8("g", { children: hitEls }),
3034
3253
  /* @__PURE__ */ jsx8("g", { pointerEvents: "none", children: [...issueMap].map(([id, sev]) => {
3035
3254
  const loc = findItem(vdoc, id);
3036
3255
  if (!loc || !layerById[vdoc.layers[loc.layerIndex].id]?.visible) return null;
@@ -3215,7 +3434,7 @@ function CanvasMenu() {
3215
3434
  ] })
3216
3435
  ] });
3217
3436
  }
3218
- const z4 = (move) => {
3437
+ const z5 = (move) => {
3219
3438
  const ps = selection.map((id) => zOrderPatch(ed.state.doc, id, move)).filter((p) => !!p);
3220
3439
  if (ps.length) ed.apply({ op: "batch", patches: ps });
3221
3440
  };
@@ -3232,19 +3451,19 @@ function CanvasMenu() {
3232
3451
  ] })
3233
3452
  ] }),
3234
3453
  /* @__PURE__ */ jsx8(ContextMenuSeparator, {}),
3235
- /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z4("front"), children: [
3454
+ /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z5("front"), children: [
3236
3455
  "Bring to front",
3237
3456
  /* @__PURE__ */ jsx8(ContextMenuShortcut, { children: "\u21E7]" })
3238
3457
  ] }),
3239
- /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z4("forward"), children: [
3458
+ /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z5("forward"), children: [
3240
3459
  "Bring forward",
3241
3460
  /* @__PURE__ */ jsx8(ContextMenuShortcut, { children: "]" })
3242
3461
  ] }),
3243
- /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z4("backward"), children: [
3462
+ /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z5("backward"), children: [
3244
3463
  "Send backward",
3245
3464
  /* @__PURE__ */ jsx8(ContextMenuShortcut, { children: "[" })
3246
3465
  ] }),
3247
- /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z4("back"), children: [
3466
+ /* @__PURE__ */ jsxs6(ContextMenuItem, { onSelect: () => z5("back"), children: [
3248
3467
  "Send to back",
3249
3468
  /* @__PURE__ */ jsx8(ContextMenuShortcut, { children: "\u21E7[" })
3250
3469
  ] }),
@@ -4982,10 +5201,10 @@ function HeaderBar({ onEmbed, onCancel, embedding, className }) {
4982
5201
  }
4983
5202
 
4984
5203
  // ../../src/patent-render/client/ChatDock.tsx
4985
- import { useEffect as useEffect2, useRef as useRef2, useState as useState6 } from "react";
5204
+ import { useEffect as useEffect2, useRef as useRef3, useState as useState6 } from "react";
4986
5205
  import {
4987
5206
  ArrowUp,
4988
- Check,
5207
+ Check as Check2,
4989
5208
  ChevronDown as ChevronDown2,
4990
5209
  ChevronUp,
4991
5210
  Circle as Circle3,
@@ -5001,71 +5220,76 @@ import {
5001
5220
  } from "lucide-react";
5002
5221
  import { cn as cn23 } from "cn";
5003
5222
 
5004
- // ../../src/patent-render/schema/plan.ts
5005
- import { z as z3 } from "zod";
5006
- var FigureType = z3.enum([
5007
- "flowchart",
5008
- "blockDiagram",
5009
- "mechanical2d",
5010
- "uiScreen",
5011
- "perspective3d",
5012
- "circuit",
5013
- "chemical"
5014
- ]);
5015
- var FigurePlan = z3.object({
5016
- figureType: FigureType,
5017
- /** e.g. "Cross-sectional view taken along line A-A of FIG. 2" */
5018
- view: z3.string(),
5019
- summary: z3.string(),
5020
- /**
5021
- * Full generation spec: overall form and proportions (mm), every component's
5022
- * shape, position and relationships, counts, surface details and what faces
5023
- * the viewer. Written so a draftsperson can draw without guessing.
5024
- */
5025
- spec: z3.string().default(""),
5026
- components: z3.array(z3.object({
5027
- numeral: z3.string(),
5028
- name: z3.string(),
5029
- description: z3.string().optional(),
5030
- reused: z3.boolean().default(false)
5031
- // numeral came from the host registry
5032
- })),
5033
- layers: z3.array(z3.object({ id: z3.string(), name: z3.string() })),
5034
- notes: z3.array(z3.string()).default([])
5035
- });
5036
- var DrawingStyle = z3.enum(["standard", "detailed", "minimal"]);
5037
- var STYLE_LABEL = {
5038
- standard: { label: "Standard line art", hint: "Clean outlines and key details, as most filings" },
5039
- detailed: { label: "Detailed rendering", hint: "Shading strokes, glare, textures, fine features" },
5040
- minimal: { label: "Minimal outline", hint: "Essential outlines only, fewest lines" }
5041
- };
5042
- var GenerationPrefs = z3.object({
5043
- figureType: FigureType.optional(),
5044
- // undefined = let the planner decide
5045
- style: DrawingStyle.default("standard")
5046
- });
5047
- var FIGURE_TYPE_LABEL = {
5048
- flowchart: "Flowchart",
5049
- blockDiagram: "Block diagram",
5050
- mechanical2d: "Mechanical 2D",
5051
- uiScreen: "UI screen",
5052
- perspective3d: "Perspective 3D",
5053
- circuit: "Circuit",
5054
- chemical: "Chemical structure"
5223
+ // ../../src/patent-render/client/InterruptedCard.tsx
5224
+ import { Check, CircleDashed as CircleDashed2, CirclePause } from "lucide-react";
5225
+ import { jsx as jsx25, jsxs as jsxs16 } from "react/jsx-runtime";
5226
+ var TITLE = {
5227
+ planning: "Planning was interrupted",
5228
+ drawing: "Drawing was interrupted",
5229
+ edit: "Your change was interrupted"
5055
5230
  };
5231
+ function choices(run) {
5232
+ if (run.kind === "drawing") {
5233
+ return [
5234
+ { action: "continue", label: "Continue drawing" },
5235
+ { action: "restart", label: "Start over" },
5236
+ { action: "dismiss", label: "Keep as is" }
5237
+ ];
5238
+ }
5239
+ if (run.kind === "edit" && run.edits > 0) {
5240
+ return [
5241
+ { action: "continue", label: "Continue change" },
5242
+ { action: "undo", label: "Undo these edits" },
5243
+ { action: "dismiss", label: "Keep as is" }
5244
+ ];
5245
+ }
5246
+ return [
5247
+ { action: "retry", label: "Try again" },
5248
+ { action: "edit", label: "Edit request" },
5249
+ { action: "dismiss", label: "Dismiss" }
5250
+ ];
5251
+ }
5252
+ function InterruptedCard({ run, onAction }) {
5253
+ return /* @__PURE__ */ jsxs16("section", { "aria-label": TITLE[run.kind], "data-slot": "pr-interrupted", className: "max-w-[min(36rem,100%)] rounded-lg border bg-card px-3 py-2.5 text-card-foreground", children: [
5254
+ /* @__PURE__ */ jsxs16("div", { className: "flex items-center gap-2 text-xs font-semibold", children: [
5255
+ /* @__PURE__ */ jsx25(CirclePause, { className: "size-3.5 text-muted-foreground" }),
5256
+ " ",
5257
+ TITLE[run.kind]
5258
+ ] }),
5259
+ run.request && /* @__PURE__ */ jsxs16("p", { className: "mt-1 line-clamp-2 text-xs text-muted-foreground", children: [
5260
+ "\u201C",
5261
+ run.request,
5262
+ "\u201D"
5263
+ ] }),
5264
+ run.kind === "drawing" && run.steps.length > 0 && /* @__PURE__ */ jsxs16("ol", { className: "mt-2 grid gap-1", children: [
5265
+ run.hiddenSteps > 0 && /* @__PURE__ */ jsxs16("li", { className: "pl-[22px] text-xs text-muted-foreground", children: [
5266
+ run.hiddenSteps,
5267
+ " earlier step",
5268
+ run.hiddenSteps === 1 ? "" : "s"
5269
+ ] }),
5270
+ run.steps.map((s, i) => /* @__PURE__ */ jsxs16("li", { className: s.status === "done" ? "flex items-center gap-2 text-xs" : "flex items-center gap-2 text-xs text-muted-foreground", children: [
5271
+ s.status === "done" ? /* @__PURE__ */ jsx25(Check, { className: "size-3.5 shrink-0 text-success" }) : /* @__PURE__ */ jsx25(CircleDashed2, { className: "size-3.5 shrink-0" }),
5272
+ s.label
5273
+ ] }, i))
5274
+ ] }),
5275
+ run.kind === "planning" && /* @__PURE__ */ jsx25("p", { className: "mt-1.5 text-xs text-muted-foreground", children: "Nothing was drawn yet. Your request is saved." }),
5276
+ run.kind === "edit" && /* @__PURE__ */ jsx25("p", { className: "mt-1.5 text-xs text-muted-foreground", children: run.edits ? `${run.edits} edit${run.edits === 1 ? " was" : "s were"} made before it stopped.` : "No edits were made before it stopped." }),
5277
+ /* @__PURE__ */ jsx25("div", { className: "mt-2.5 flex flex-wrap gap-1.5", children: choices(run).map((c, i) => /* @__PURE__ */ jsx25(Button, { size: "sm", variant: i === 0 ? "default" : "outline", className: "h-7 text-xs", onClick: () => onAction(c.action), children: c.label }, c.action)) })
5278
+ ] });
5279
+ }
5056
5280
 
5057
5281
  // ../../src/patent-render/ui/collapsible.tsx
5058
5282
  import { Collapsible as CollapsiblePrimitive } from "radix-ui";
5059
- import { jsx as jsx25 } from "react/jsx-runtime";
5283
+ import { jsx as jsx26 } from "react/jsx-runtime";
5060
5284
  function Collapsible({
5061
5285
  ...props
5062
5286
  }) {
5063
- return /* @__PURE__ */ jsx25(CollapsiblePrimitive.Root, { "data-slot": "collapsible", ...props });
5287
+ return /* @__PURE__ */ jsx26(CollapsiblePrimitive.Root, { "data-slot": "collapsible", ...props });
5064
5288
  }
5065
5289
  function CollapsibleTrigger({
5066
5290
  ...props
5067
5291
  }) {
5068
- return /* @__PURE__ */ jsx25(
5292
+ return /* @__PURE__ */ jsx26(
5069
5293
  CollapsiblePrimitive.CollapsibleTrigger,
5070
5294
  {
5071
5295
  "data-slot": "collapsible-trigger",
@@ -5076,7 +5300,7 @@ function CollapsibleTrigger({
5076
5300
  function CollapsibleContent({
5077
5301
  ...props
5078
5302
  }) {
5079
- return /* @__PURE__ */ jsx25(
5303
+ return /* @__PURE__ */ jsx26(
5080
5304
  CollapsiblePrimitive.CollapsibleContent,
5081
5305
  {
5082
5306
  "data-slot": "collapsible-content",
@@ -5086,7 +5310,7 @@ function CollapsibleContent({
5086
5310
  }
5087
5311
 
5088
5312
  // ../../src/patent-render/client/ChatDock.tsx
5089
- import { jsx as jsx26, jsxs as jsxs16 } from "react/jsx-runtime";
5313
+ import { jsx as jsx27, jsxs as jsxs17 } from "react/jsx-runtime";
5090
5314
  var SUGGESTIONS = [
5091
5315
  "Flowchart of the method in claim 1",
5092
5316
  "Block diagram of the system with server, network and client devices",
@@ -5096,75 +5320,75 @@ var SUGGESTIONS = [
5096
5320
  var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
5097
5321
  function PlanCard({ plan, onEdit, defaultOpen = true }) {
5098
5322
  const [open, setOpen] = useState6(defaultOpen);
5099
- return /* @__PURE__ */ jsxs16(Collapsible, { open, onOpenChange: setOpen, className: "overflow-hidden rounded-lg border bg-card text-card-foreground", children: [
5100
- /* @__PURE__ */ jsxs16(CollapsibleTrigger, { className: "flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-accent/40", children: [
5101
- /* @__PURE__ */ jsx26(Sparkles, { className: "size-3.5 text-muted-foreground" }),
5102
- /* @__PURE__ */ jsx26("span", { className: "text-xs font-semibold", children: "Figure plan" }),
5103
- /* @__PURE__ */ jsx26(Badge, { variant: "secondary", className: "h-5 px-1.5 text-[10px]", children: FIGURE_TYPE_LABEL[plan.figureType] }),
5104
- /* @__PURE__ */ jsx26("span", { className: "min-w-0 flex-1 truncate text-xs text-muted-foreground", children: plan.view }),
5105
- /* @__PURE__ */ jsx26(ChevronDown2, { className: cn23("size-3.5 text-muted-foreground transition-transform", open && "rotate-180") })
5323
+ return /* @__PURE__ */ jsxs17(Collapsible, { open, onOpenChange: setOpen, className: "overflow-hidden rounded-lg border bg-card text-card-foreground", children: [
5324
+ /* @__PURE__ */ jsxs17(CollapsibleTrigger, { className: "flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-accent/40", children: [
5325
+ /* @__PURE__ */ jsx27(Sparkles, { className: "size-3.5 text-muted-foreground" }),
5326
+ /* @__PURE__ */ jsx27("span", { className: "text-xs font-semibold", children: "Figure plan" }),
5327
+ /* @__PURE__ */ jsx27(Badge, { variant: "secondary", className: "h-5 px-1.5 text-[10px]", children: FIGURE_TYPE_LABEL[plan.figureType] }),
5328
+ /* @__PURE__ */ jsx27("span", { className: "min-w-0 flex-1 truncate text-xs text-muted-foreground", children: plan.view }),
5329
+ /* @__PURE__ */ jsx27(ChevronDown2, { className: cn23("size-3.5 text-muted-foreground transition-transform", open && "rotate-180") })
5106
5330
  ] }),
5107
- /* @__PURE__ */ jsx26(CollapsibleContent, { children: /* @__PURE__ */ jsxs16("div", { className: "grid gap-3 border-t px-3 py-2.5", children: [
5108
- /* @__PURE__ */ jsx26("p", { className: "text-xs leading-relaxed", children: plan.summary }),
5109
- plan.spec && /* @__PURE__ */ jsxs16("details", { className: "group rounded-md bg-muted/50 px-2 py-1.5", children: [
5110
- /* @__PURE__ */ jsx26("summary", { className: "cursor-pointer text-[10px] font-semibold tracking-wide text-muted-foreground uppercase select-none", children: "Full spec" }),
5111
- /* @__PURE__ */ jsx26("p", { className: "mt-1.5 text-xs leading-relaxed whitespace-pre-wrap", children: plan.spec })
5331
+ /* @__PURE__ */ jsx27(CollapsibleContent, { children: /* @__PURE__ */ jsxs17("div", { className: "grid gap-3 border-t px-3 py-2.5", children: [
5332
+ /* @__PURE__ */ jsx27("p", { className: "text-xs leading-relaxed", children: plan.summary }),
5333
+ plan.spec && /* @__PURE__ */ jsxs17("details", { className: "group rounded-md bg-muted/50 px-2 py-1.5", children: [
5334
+ /* @__PURE__ */ jsx27("summary", { className: "cursor-pointer text-[10px] font-semibold tracking-wide text-muted-foreground uppercase select-none", children: "Full spec" }),
5335
+ /* @__PURE__ */ jsx27("p", { className: "mt-1.5 text-xs leading-relaxed whitespace-pre-wrap", children: plan.spec })
5112
5336
  ] }),
5113
- /* @__PURE__ */ jsxs16("div", { children: [
5114
- /* @__PURE__ */ jsx26("div", { className: "mb-1 text-[10px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Reference numerals" }),
5115
- /* @__PURE__ */ jsx26("table", { className: "w-full text-xs", children: /* @__PURE__ */ jsx26("tbody", { children: plan.components.map((c) => /* @__PURE__ */ jsxs16("tr", { className: "align-top", children: [
5116
- /* @__PURE__ */ jsx26("td", { className: "w-12 py-0.5 font-medium tabular-nums", children: c.numeral }),
5117
- /* @__PURE__ */ jsxs16("td", { className: "py-0.5", children: [
5337
+ /* @__PURE__ */ jsxs17("div", { children: [
5338
+ /* @__PURE__ */ jsx27("div", { className: "mb-1 text-[10px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Reference numerals" }),
5339
+ /* @__PURE__ */ jsx27("table", { className: "w-full text-xs", children: /* @__PURE__ */ jsx27("tbody", { children: plan.components.map((c) => /* @__PURE__ */ jsxs17("tr", { className: "align-top", children: [
5340
+ /* @__PURE__ */ jsx27("td", { className: "w-12 py-0.5 font-medium tabular-nums", children: c.numeral }),
5341
+ /* @__PURE__ */ jsxs17("td", { className: "py-0.5", children: [
5118
5342
  c.name,
5119
- c.reused && /* @__PURE__ */ jsx26("span", { className: "ml-1.5 text-[10px] text-muted-foreground", children: "from spec" })
5343
+ c.reused && /* @__PURE__ */ jsx27("span", { className: "ml-1.5 text-[10px] text-muted-foreground", children: "from spec" })
5120
5344
  ] })
5121
5345
  ] }, c.numeral)) }) })
5122
5346
  ] }),
5123
- /* @__PURE__ */ jsxs16("div", { className: "flex flex-wrap items-center gap-1", children: [
5124
- /* @__PURE__ */ jsx26("span", { className: "mr-1 text-[10px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Layers" }),
5125
- plan.layers.map((l) => /* @__PURE__ */ jsx26(Badge, { variant: "outline", className: "h-5 px-1.5 text-[10px] font-normal", children: l.name }, l.id))
5347
+ /* @__PURE__ */ jsxs17("div", { className: "flex flex-wrap items-center gap-1", children: [
5348
+ /* @__PURE__ */ jsx27("span", { className: "mr-1 text-[10px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Layers" }),
5349
+ plan.layers.map((l) => /* @__PURE__ */ jsx27(Badge, { variant: "outline", className: "h-5 px-1.5 text-[10px] font-normal", children: l.name }, l.id))
5126
5350
  ] }),
5127
- plan.notes.length > 0 && /* @__PURE__ */ jsx26("ul", { className: "grid gap-0.5 text-[11px] text-muted-foreground", children: plan.notes.map((n, i) => /* @__PURE__ */ jsxs16("li", { children: [
5351
+ plan.notes.length > 0 && /* @__PURE__ */ jsx27("ul", { className: "grid gap-0.5 text-[11px] text-muted-foreground", children: plan.notes.map((n, i) => /* @__PURE__ */ jsxs17("li", { children: [
5128
5352
  "\xB7 ",
5129
5353
  n
5130
5354
  ] }, i)) }),
5131
- onEdit && /* @__PURE__ */ jsx26("div", { children: /* @__PURE__ */ jsxs16(Button, { variant: "outline", size: "sm", className: "h-7 text-xs", onClick: () => onEdit(plan), children: [
5132
- /* @__PURE__ */ jsx26(Pencil, { className: "size-3" }),
5355
+ onEdit && /* @__PURE__ */ jsx27("div", { children: /* @__PURE__ */ jsxs17(Button, { variant: "outline", size: "sm", className: "h-7 text-xs", onClick: () => onEdit(plan), children: [
5356
+ /* @__PURE__ */ jsx27(Pencil, { className: "size-3" }),
5133
5357
  " Edit plan and redraw"
5134
5358
  ] }) })
5135
5359
  ] }) })
5136
5360
  ] });
5137
5361
  }
5138
5362
  function Progress({ steps }) {
5139
- return /* @__PURE__ */ jsx26("ol", { className: "grid gap-1", children: steps.map((s, i) => /* @__PURE__ */ jsxs16("li", { className: cn23("flex items-center gap-2 text-xs", s.status === "pending" && "text-muted-foreground"), children: [
5140
- s.status === "done" ? /* @__PURE__ */ jsx26(Check, { className: "size-3.5 text-success" }) : s.status === "active" ? /* @__PURE__ */ jsx26(Loader22, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ jsx26(Circle3, { className: "size-3.5" }),
5363
+ return /* @__PURE__ */ jsx27("ol", { className: "grid gap-1", children: steps.map((s, i) => /* @__PURE__ */ jsxs17("li", { className: cn23("flex items-center gap-2 text-xs", s.status === "pending" && "text-muted-foreground"), children: [
5364
+ s.status === "done" ? /* @__PURE__ */ jsx27(Check2, { className: "size-3.5 text-success" }) : s.status === "active" ? /* @__PURE__ */ jsx27(Loader22, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ jsx27(Circle3, { className: "size-3.5" }),
5141
5365
  s.label
5142
5366
  ] }, i)) });
5143
5367
  }
5144
5368
  function withBold(text) {
5145
5369
  return text.split(/(\*\*[^*]+\*\*)/g).map(
5146
- (s, i) => s.startsWith("**") && s.endsWith("**") ? /* @__PURE__ */ jsx26("strong", { children: s.slice(2, -2) }, i) : s
5370
+ (s, i) => s.startsWith("**") && s.endsWith("**") ? /* @__PURE__ */ jsx27("strong", { children: s.slice(2, -2) }, i) : s
5147
5371
  );
5148
5372
  }
5149
5373
  function Part({ part, onEditPlan }) {
5150
5374
  switch (part.type) {
5151
5375
  case "text":
5152
- return /* @__PURE__ */ jsx26("p", { className: "text-[13px] leading-relaxed whitespace-pre-wrap", children: withBold(part.text) });
5376
+ return /* @__PURE__ */ jsx27("p", { className: "text-[13px] leading-relaxed whitespace-pre-wrap", children: withBold(part.text) });
5153
5377
  case "image":
5154
5378
  return (
5155
5379
  // eslint-disable-next-line @next/next/no-img-element
5156
- /* @__PURE__ */ jsx26("img", { src: part.url, alt: part.name, className: "max-h-32 rounded-md border object-contain" })
5380
+ /* @__PURE__ */ jsx27("img", { src: part.url, alt: part.name, className: "max-h-32 rounded-md border object-contain" })
5157
5381
  );
5158
5382
  case "plan":
5159
- return /* @__PURE__ */ jsx26(PlanCard, { plan: part.plan, onEdit: onEditPlan });
5383
+ return /* @__PURE__ */ jsx27(PlanCard, { plan: part.plan, onEdit: onEditPlan });
5160
5384
  case "progress":
5161
- return /* @__PURE__ */ jsx26(Progress, { steps: part.steps });
5385
+ return /* @__PURE__ */ jsx27(Progress, { steps: part.steps });
5162
5386
  case "edits":
5163
- return /* @__PURE__ */ jsxs16("div", { className: "inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs", children: [
5164
- /* @__PURE__ */ jsx26(Wand2, { className: "size-3" }),
5387
+ return /* @__PURE__ */ jsxs17("div", { className: "inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs", children: [
5388
+ /* @__PURE__ */ jsx27(Wand2, { className: "size-3" }),
5165
5389
  " ",
5166
5390
  part.summary,
5167
- /* @__PURE__ */ jsxs16("span", { className: "text-muted-foreground", children: [
5391
+ /* @__PURE__ */ jsxs17("span", { className: "text-muted-foreground", children: [
5168
5392
  "\xB7 ",
5169
5393
  part.count,
5170
5394
  " change",
@@ -5172,8 +5396,8 @@ function Part({ part, onEditPlan }) {
5172
5396
  ] })
5173
5397
  ] });
5174
5398
  case "error":
5175
- return /* @__PURE__ */ jsxs16("div", { className: "flex items-start gap-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-xs text-destructive", children: [
5176
- /* @__PURE__ */ jsx26(TriangleAlert2, { className: "mt-0.5 size-3.5 shrink-0" }),
5399
+ return /* @__PURE__ */ jsxs17("div", { className: "flex items-start gap-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-xs text-destructive", children: [
5400
+ /* @__PURE__ */ jsx27(TriangleAlert2, { className: "mt-0.5 size-3.5 shrink-0" }),
5177
5401
  " ",
5178
5402
  part.message
5179
5403
  ] });
@@ -5181,32 +5405,32 @@ function Part({ part, onEditPlan }) {
5181
5405
  }
5182
5406
  function Message({ m, onEditPlan }) {
5183
5407
  const user = m.role === "user";
5184
- return /* @__PURE__ */ jsx26("div", { className: cn23("flex", user ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx26("div", { className: cn23("grid max-w-[min(36rem,85%)] gap-2", user && "justify-items-end rounded-2xl rounded-br-md bg-primary px-3 py-2 text-primary-foreground"), children: m.parts.map((p, i) => /* @__PURE__ */ jsx26(Part, { part: p, onEditPlan }, i)) }) });
5408
+ return /* @__PURE__ */ jsx27("div", { className: cn23("flex", user ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx27("div", { className: cn23("grid max-w-[min(36rem,85%)] gap-2", user && "justify-items-end rounded-2xl rounded-br-md bg-primary px-3 py-2 text-primary-foreground"), children: m.parts.map((p, i) => /* @__PURE__ */ jsx27(Part, { part: p, onEditPlan }, i)) }) });
5185
5409
  }
5186
5410
  function PrefPicker({ label, value, display, options, onChange, disabled }) {
5187
- return /* @__PURE__ */ jsxs16(DropdownMenu, { children: [
5188
- /* @__PURE__ */ jsx26(DropdownMenuTrigger, { asChild: true, disabled, children: /* @__PURE__ */ jsxs16(
5411
+ return /* @__PURE__ */ jsxs17(DropdownMenu, { children: [
5412
+ /* @__PURE__ */ jsx27(DropdownMenuTrigger, { asChild: true, disabled, children: /* @__PURE__ */ jsxs17(
5189
5413
  "button",
5190
5414
  {
5191
5415
  type: "button",
5192
5416
  "aria-label": `${label}: ${display}`,
5193
5417
  className: "inline-flex h-7 items-center gap-1 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50",
5194
5418
  children: [
5195
- /* @__PURE__ */ jsxs16("span", { children: [
5419
+ /* @__PURE__ */ jsxs17("span", { children: [
5196
5420
  label,
5197
5421
  ":"
5198
5422
  ] }),
5199
- /* @__PURE__ */ jsx26("span", { className: "font-medium text-foreground", children: display }),
5200
- /* @__PURE__ */ jsx26(ChevronDown2, { className: "size-3" })
5423
+ /* @__PURE__ */ jsx27("span", { className: "font-medium text-foreground", children: display }),
5424
+ /* @__PURE__ */ jsx27(ChevronDown2, { className: "size-3" })
5201
5425
  ]
5202
5426
  }
5203
5427
  ) }),
5204
- /* @__PURE__ */ jsxs16(DropdownMenuContent, { align: "start", side: "top", className: "w-60", children: [
5205
- /* @__PURE__ */ jsx26(DropdownMenuLabel, { className: "text-xs", children: label }),
5206
- /* @__PURE__ */ jsx26(DropdownMenuSeparator, {}),
5207
- /* @__PURE__ */ jsx26(DropdownMenuRadioGroup, { value, onValueChange: onChange, children: options.map((o) => /* @__PURE__ */ jsx26(DropdownMenuRadioItem, { value: o.value, className: "items-start text-xs", children: /* @__PURE__ */ jsxs16("div", { children: [
5208
- /* @__PURE__ */ jsx26("div", { children: o.label }),
5209
- o.hint && /* @__PURE__ */ jsx26("div", { className: "text-[11px] text-muted-foreground", children: o.hint })
5428
+ /* @__PURE__ */ jsxs17(DropdownMenuContent, { align: "start", side: "top", className: "w-60", children: [
5429
+ /* @__PURE__ */ jsx27(DropdownMenuLabel, { className: "text-xs", children: label }),
5430
+ /* @__PURE__ */ jsx27(DropdownMenuSeparator, {}),
5431
+ /* @__PURE__ */ jsx27(DropdownMenuRadioGroup, { value, onValueChange: onChange, children: options.map((o) => /* @__PURE__ */ jsx27(DropdownMenuRadioItem, { value: o.value, className: "items-start text-xs", children: /* @__PURE__ */ jsxs17("div", { children: [
5432
+ /* @__PURE__ */ jsx27("div", { children: o.label }),
5433
+ o.hint && /* @__PURE__ */ jsx27("div", { className: "text-[11px] text-muted-foreground", children: o.hint })
5210
5434
  ] }) }, o.value)) })
5211
5435
  ] })
5212
5436
  ] });
@@ -5221,7 +5445,9 @@ function ChatDock({
5221
5445
  className,
5222
5446
  historyHeight,
5223
5447
  collapsed: collapsedProp,
5224
- onCollapsedChange
5448
+ onCollapsedChange,
5449
+ interrupted,
5450
+ onInterrupted
5225
5451
  }) {
5226
5452
  const [text, setText] = useState6("");
5227
5453
  const [files, setFiles] = useState6([]);
@@ -5230,14 +5456,14 @@ function ChatDock({
5230
5456
  const collapsed = collapsedProp ?? collapsedLocal;
5231
5457
  const setCollapsed = (v) => onCollapsedChange ? onCollapsedChange(v) : setCollapsedLocal(v);
5232
5458
  const [dragOver, setDragOver] = useState6(false);
5233
- const scrollRef = useRef2(null);
5234
- const fileRef = useRef2(null);
5235
- const taRef = useRef2(null);
5459
+ const scrollRef = useRef3(null);
5460
+ const fileRef = useRef3(null);
5461
+ const taRef = useRef3(null);
5236
5462
  const running = status !== "idle";
5237
- const empty = messages.length === 0;
5463
+ const empty = messages.length === 0 && !interrupted;
5238
5464
  useEffect2(() => {
5239
5465
  scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
5240
- }, [messages]);
5466
+ }, [messages, interrupted?.id]);
5241
5467
  useEffect2(() => {
5242
5468
  const ta = taRef.current;
5243
5469
  if (!ta) return;
@@ -5256,7 +5482,15 @@ function ChatDock({
5256
5482
  setText("");
5257
5483
  setFiles([]);
5258
5484
  };
5259
- return /* @__PURE__ */ jsxs16(
5485
+ const onInterruptedAction = (action) => {
5486
+ if (action === "edit" && interrupted) {
5487
+ setText(interrupted.request);
5488
+ setFiles(interrupted.attachments);
5489
+ taRef.current?.focus();
5490
+ }
5491
+ onInterrupted?.(action);
5492
+ };
5493
+ return /* @__PURE__ */ jsxs17(
5260
5494
  "div",
5261
5495
  {
5262
5496
  className: cn23("flex min-h-0 flex-col border-t bg-background", className),
@@ -5276,21 +5510,24 @@ function ChatDock({
5276
5510
  setDragOver(false);
5277
5511
  },
5278
5512
  children: [
5279
- (!empty || onCollapsedChange) && /* @__PURE__ */ jsxs16("div", { className: "flex h-8 shrink-0 items-center justify-between px-3", children: [
5280
- /* @__PURE__ */ jsx26("span", { className: "text-[11px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Assistant" }),
5281
- /* @__PURE__ */ jsx26(Button, { variant: "ghost", size: "icon", className: "size-6", "aria-label": collapsed ? "Expand chat" : "Collapse chat", onClick: () => setCollapsed(!collapsed), children: collapsed ? /* @__PURE__ */ jsx26(ChevronUp, { className: "size-3.5" }) : /* @__PURE__ */ jsx26(ChevronDown2, { className: "size-3.5" }) })
5513
+ (!empty || onCollapsedChange) && /* @__PURE__ */ jsxs17("div", { className: "flex h-8 shrink-0 items-center justify-between px-3", children: [
5514
+ /* @__PURE__ */ jsx27("span", { className: "text-[11px] font-semibold tracking-wide text-muted-foreground uppercase", children: "Assistant" }),
5515
+ /* @__PURE__ */ jsx27(Button, { variant: "ghost", size: "icon", className: "size-6", "aria-label": collapsed ? "Expand chat" : "Collapse chat", onClick: () => setCollapsed(!collapsed), children: collapsed ? /* @__PURE__ */ jsx27(ChevronUp, { className: "size-3.5" }) : /* @__PURE__ */ jsx27(ChevronDown2, { className: "size-3.5" }) })
5282
5516
  ] }),
5283
- !collapsed && !empty && /* @__PURE__ */ jsx26(
5517
+ !collapsed && !empty && /* @__PURE__ */ jsx27(
5284
5518
  "div",
5285
5519
  {
5286
5520
  ref: scrollRef,
5287
5521
  className: cn23("min-h-0 overflow-y-auto px-3 pb-2", historyHeight === void 0 && "max-h-[min(15rem,32vh)]"),
5288
5522
  style: historyHeight !== void 0 ? { height: historyHeight } : void 0,
5289
- children: /* @__PURE__ */ jsx26("div", { className: "mx-auto grid max-w-3xl gap-3", children: messages.map((m) => /* @__PURE__ */ jsx26(Message, { m, onEditPlan: running ? void 0 : onEditPlan }, m.id)) })
5523
+ children: /* @__PURE__ */ jsxs17("div", { className: "mx-auto grid max-w-3xl gap-3", children: [
5524
+ messages.map((m) => /* @__PURE__ */ jsx27(Message, { m, onEditPlan: running ? void 0 : onEditPlan }, m.id)),
5525
+ interrupted && /* @__PURE__ */ jsx27(InterruptedCard, { run: interrupted, onAction: onInterruptedAction })
5526
+ ] })
5290
5527
  }
5291
5528
  ),
5292
- /* @__PURE__ */ jsx26("div", { className: "shrink-0 px-3 pt-1 pb-3", children: /* @__PURE__ */ jsxs16("div", { className: "mx-auto max-w-3xl", children: [
5293
- empty && !collapsed && /* @__PURE__ */ jsx26("div", { className: "mb-2 flex flex-wrap gap-1.5", children: SUGGESTIONS.map((s) => /* @__PURE__ */ jsx26(
5529
+ /* @__PURE__ */ jsx27("div", { className: "shrink-0 px-3 pt-1 pb-3", children: /* @__PURE__ */ jsxs17("div", { className: "mx-auto max-w-3xl", children: [
5530
+ empty && !collapsed && /* @__PURE__ */ jsx27("div", { className: "mb-2 flex flex-wrap gap-1.5", children: SUGGESTIONS.map((s) => /* @__PURE__ */ jsx27(
5294
5531
  "button",
5295
5532
  {
5296
5533
  type: "button",
@@ -5303,24 +5540,24 @@ function ChatDock({
5303
5540
  },
5304
5541
  s
5305
5542
  )) }),
5306
- /* @__PURE__ */ jsxs16("div", { className: cn23(
5543
+ /* @__PURE__ */ jsxs17("div", { className: cn23(
5307
5544
  "rounded-xl border bg-background shadow-sm transition-shadow focus-within:ring-2 focus-within:ring-ring/40",
5308
5545
  dragOver && "ring-2 ring-ring"
5309
5546
  ), children: [
5310
- files.length > 0 && /* @__PURE__ */ jsx26("div", { className: "flex flex-wrap items-center gap-1.5 px-2 pt-2", children: files.map((f) => /* @__PURE__ */ jsxs16("div", { className: "group relative", children: [
5311
- /* @__PURE__ */ jsx26("img", { src: f.url, alt: f.name, className: "size-12 rounded-md border object-cover" }),
5312
- /* @__PURE__ */ jsx26(
5547
+ files.length > 0 && /* @__PURE__ */ jsx27("div", { className: "flex flex-wrap items-center gap-1.5 px-2 pt-2", children: files.map((f) => /* @__PURE__ */ jsxs17("div", { className: "group relative", children: [
5548
+ /* @__PURE__ */ jsx27("img", { src: f.url, alt: f.name, className: "size-12 rounded-md border object-cover" }),
5549
+ /* @__PURE__ */ jsx27(
5313
5550
  "button",
5314
5551
  {
5315
5552
  type: "button",
5316
5553
  "aria-label": `Remove ${f.name}`,
5317
5554
  className: "absolute -top-1.5 -right-1.5 hidden size-4 items-center justify-center rounded-full bg-foreground text-background group-hover:flex",
5318
5555
  onClick: () => setFiles(files.filter((x) => x.id !== f.id)),
5319
- children: /* @__PURE__ */ jsx26(X, { className: "size-2.5" })
5556
+ children: /* @__PURE__ */ jsx27(X, { className: "size-2.5" })
5320
5557
  }
5321
5558
  )
5322
5559
  ] }, f.id)) }),
5323
- /* @__PURE__ */ jsx26(
5560
+ /* @__PURE__ */ jsx27(
5324
5561
  "textarea",
5325
5562
  {
5326
5563
  ref: taRef,
@@ -5339,14 +5576,14 @@ function ChatDock({
5339
5576
  className: "block w-full resize-none bg-transparent px-3 py-2.5 text-sm outline-none placeholder:text-muted-foreground"
5340
5577
  }
5341
5578
  ),
5342
- /* @__PURE__ */ jsxs16("div", { className: "flex items-center justify-between px-1.5 pb-1.5", children: [
5343
- /* @__PURE__ */ jsxs16("div", { className: "flex min-w-0 items-center gap-1.5", children: [
5344
- /* @__PURE__ */ jsx26("input", { ref: fileRef, type: "file", accept: "image/*", multiple: true, hidden: true, onChange: (e) => {
5579
+ /* @__PURE__ */ jsxs17("div", { className: "flex items-center justify-between px-1.5 pb-1.5", children: [
5580
+ /* @__PURE__ */ jsxs17("div", { className: "flex min-w-0 items-center gap-1.5", children: [
5581
+ /* @__PURE__ */ jsx27("input", { ref: fileRef, type: "file", accept: "image/*", multiple: true, hidden: true, onChange: (e) => {
5345
5582
  addFiles(e.target.files);
5346
5583
  e.target.value = "";
5347
5584
  } }),
5348
- /* @__PURE__ */ jsx26(Button, { variant: "ghost", size: "icon", className: "size-7", "aria-label": "Attach reference image", disabled: running, onClick: () => fileRef.current?.click(), children: /* @__PURE__ */ jsx26(ImagePlus, { className: "size-4" }) }),
5349
- /* @__PURE__ */ jsx26(
5585
+ /* @__PURE__ */ jsx27(Button, { variant: "ghost", size: "icon", className: "size-7", "aria-label": "Attach reference image", disabled: running, onClick: () => fileRef.current?.click(), children: /* @__PURE__ */ jsx27(ImagePlus, { className: "size-4" }) }),
5586
+ /* @__PURE__ */ jsx27(
5350
5587
  PrefPicker,
5351
5588
  {
5352
5589
  label: "Figure",
@@ -5357,7 +5594,7 @@ function ChatDock({
5357
5594
  disabled: running
5358
5595
  }
5359
5596
  ),
5360
- /* @__PURE__ */ jsx26(
5597
+ /* @__PURE__ */ jsx27(
5361
5598
  PrefPicker,
5362
5599
  {
5363
5600
  label: "Style",
@@ -5368,15 +5605,15 @@ function ChatDock({
5368
5605
  disabled: running
5369
5606
  }
5370
5607
  ),
5371
- selectionCount > 0 && /* @__PURE__ */ jsxs16(Badge, { variant: "secondary", className: "h-6 gap-1 truncate text-[11px] font-normal", children: [
5372
- /* @__PURE__ */ jsx26(MousePointerClick, { className: "size-3" }),
5608
+ selectionCount > 0 && /* @__PURE__ */ jsxs17(Badge, { variant: "secondary", className: "h-6 gap-1 truncate text-[11px] font-normal", children: [
5609
+ /* @__PURE__ */ jsx27(MousePointerClick, { className: "size-3" }),
5373
5610
  " Editing ",
5374
5611
  selectionCount,
5375
5612
  " selected item",
5376
5613
  selectionCount === 1 ? "" : "s"
5377
5614
  ] })
5378
5615
  ] }),
5379
- running ? /* @__PURE__ */ jsx26(Button, { size: "icon", variant: "secondary", className: "size-7 rounded-full", "aria-label": "Stop", onClick: onStop, children: /* @__PURE__ */ jsx26(Square3, { className: "size-3 fill-current" }) }) : /* @__PURE__ */ jsx26(Button, { size: "icon", className: "size-7 rounded-full", "aria-label": "Send", disabled: !text.trim() && !files.length, onClick: send, children: /* @__PURE__ */ jsx26(ArrowUp, { className: "size-4" }) })
5616
+ running ? /* @__PURE__ */ jsx27(Button, { size: "icon", variant: "secondary", className: "size-7 rounded-full", "aria-label": "Stop", onClick: onStop, children: /* @__PURE__ */ jsx27(Square3, { className: "size-3 fill-current" }) }) : /* @__PURE__ */ jsx27(Button, { size: "icon", className: "size-7 rounded-full", "aria-label": "Send", disabled: !text.trim() && !files.length, onClick: send, children: /* @__PURE__ */ jsx27(ArrowUp, { className: "size-4" }) })
5380
5617
  ] })
5381
5618
  ] })
5382
5619
  ] }) })
@@ -5385,20 +5622,49 @@ function ChatDock({
5385
5622
  );
5386
5623
  }
5387
5624
 
5625
+ // ../../src/patent-render/ui/confirm-dialog.tsx
5626
+ import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
5627
+ import { Fragment as Fragment6, jsx as jsx28, jsxs as jsxs18 } from "react/jsx-runtime";
5628
+ function ConfirmDialog({ open, title, children, confirmLabel, cancelLabel, destructive, safe = "cancel", onConfirm, onCancel }) {
5629
+ return /* @__PURE__ */ jsxs18(AlertDialogPrimitive.Root, { open, onOpenChange: (o) => {
5630
+ if (!o) onCancel();
5631
+ }, children: [
5632
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Overlay, { className: "absolute inset-0 z-50 bg-black/45" }),
5633
+ /* @__PURE__ */ jsx28("div", { className: "pointer-events-none absolute inset-0 z-50 grid place-items-center p-4", children: /* @__PURE__ */ jsxs18(
5634
+ AlertDialogPrimitive.Content,
5635
+ {
5636
+ "data-slot": "pr-confirm",
5637
+ className: "pointer-events-auto w-full max-w-sm rounded-xl border bg-background p-5 text-foreground shadow-lg outline-none",
5638
+ children: [
5639
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Title, { className: "text-sm font-semibold", children: title }),
5640
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Description, { className: "mt-1.5 text-[13px] leading-relaxed text-muted-foreground", children }),
5641
+ /* @__PURE__ */ jsx28("div", { className: "mt-4 flex flex-wrap justify-end gap-2", children: safe === "cancel" ? /* @__PURE__ */ jsxs18(Fragment6, { children: [
5642
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Action, { asChild: true, children: /* @__PURE__ */ jsx28(Button, { variant: "outline", size: "sm", onClick: onConfirm, children: confirmLabel }) }),
5643
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Cancel, { asChild: true, children: /* @__PURE__ */ jsx28(Button, { size: "sm", children: cancelLabel }) })
5644
+ ] }) : /* @__PURE__ */ jsxs18(Fragment6, { children: [
5645
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Cancel, { asChild: true, children: /* @__PURE__ */ jsx28(Button, { variant: "outline", size: "sm", children: cancelLabel }) }),
5646
+ /* @__PURE__ */ jsx28(AlertDialogPrimitive.Action, { asChild: true, children: /* @__PURE__ */ jsx28(Button, { variant: destructive ? "destructive" : "default", size: "sm", onClick: onConfirm, children: confirmLabel }) })
5647
+ ] }) })
5648
+ ]
5649
+ }
5650
+ ) })
5651
+ ] });
5652
+ }
5653
+
5388
5654
  // ../../src/patent-render/client/PatentRenderEditor.tsx
5389
5655
  import { PanelRightClose, PanelRightOpen } from "lucide-react";
5390
5656
 
5391
5657
  // ../../src/patent-render/client/layout.tsx
5392
- import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef3, useState as useState7 } from "react";
5658
+ import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef4, useState as useState7 } from "react";
5393
5659
  import { cn as cn24 } from "cn";
5394
- import { jsx as jsx27 } from "react/jsx-runtime";
5660
+ import { jsx as jsx29 } from "react/jsx-runtime";
5395
5661
  var DEFAULT = { sideWidth: 288, sideOpen: true, split: 0.5, chatHeight: 220, chatOpen: true };
5396
5662
  var KEY = "patent-render:layout:v1";
5397
5663
  var LIMITS = { side: [220, 520], chat: [80, 560], split: [0.15, 0.85] };
5398
5664
  var clamp = (v, [lo, hi]) => Math.min(hi, Math.max(lo, v));
5399
5665
  function usePanelLayout() {
5400
5666
  const [layout, setLayout] = useState7(DEFAULT);
5401
- const loaded = useRef3(false);
5667
+ const loaded = useRef4(false);
5402
5668
  useEffect3(() => {
5403
5669
  try {
5404
5670
  const raw = localStorage.getItem(KEY);
@@ -5421,7 +5687,7 @@ function usePanelLayout() {
5421
5687
  return { layout, update };
5422
5688
  }
5423
5689
  function ResizeHandle({ axis, onDrag, onToggle, label, className }) {
5424
- const last = useRef3(null);
5690
+ const last = useRef4(null);
5425
5691
  const [active, setActive] = useState7(false);
5426
5692
  const down = (e) => {
5427
5693
  if (e.button !== 0) return;
@@ -5439,7 +5705,7 @@ function ResizeHandle({ axis, onDrag, onToggle, label, className }) {
5439
5705
  last.current = null;
5440
5706
  setActive(false);
5441
5707
  };
5442
- return /* @__PURE__ */ jsx27(
5708
+ return /* @__PURE__ */ jsx29(
5443
5709
  "div",
5444
5710
  {
5445
5711
  role: "separator",
@@ -5472,7 +5738,7 @@ function ResizeHandle({ axis, onDrag, onToggle, label, className }) {
5472
5738
  axis === "x" ? "-mx-1 w-2 cursor-col-resize" : "-my-1 h-2 cursor-row-resize",
5473
5739
  className
5474
5740
  ),
5475
- children: /* @__PURE__ */ jsx27("span", { className: cn24(
5741
+ children: /* @__PURE__ */ jsx29("span", { className: cn24(
5476
5742
  "absolute rounded-full bg-ring/0 transition-colors group-hover:bg-ring/50 group-focus-visible:bg-ring/70",
5477
5743
  axis === "x" ? "inset-y-0 left-1/2 w-0.5 -translate-x-1/2" : "inset-x-0 top-1/2 h-0.5 -translate-y-1/2",
5478
5744
  active && "bg-ring/70"
@@ -5482,24 +5748,24 @@ function ResizeHandle({ axis, onDrag, onToggle, label, className }) {
5482
5748
  }
5483
5749
 
5484
5750
  // ../../src/patent-render/client/PatentRenderEditor.tsx
5485
- import { Fragment as Fragment6, jsx as jsx28, jsxs as jsxs17 } from "react/jsx-runtime";
5751
+ import { Fragment as Fragment7, jsx as jsx30, jsxs as jsxs19 } from "react/jsx-runtime";
5486
5752
  function PatentRenderEditor(props) {
5487
- return /* @__PURE__ */ jsx28(TooltipProvider, { delayDuration: 400, children: /* @__PURE__ */ jsxs17(EditorProvider, { doc: props.document, initial: { agent: props.agentStatus ?? "idle", ...props.initialState }, children: [
5488
- /* @__PURE__ */ jsx28(PatentRenderShell, { ...props }),
5753
+ return /* @__PURE__ */ jsx30(TooltipProvider, { delayDuration: 400, children: /* @__PURE__ */ jsxs19(EditorProvider, { doc: props.document, initial: { agent: props.agentStatus ?? "idle", ...props.initialState }, children: [
5754
+ /* @__PURE__ */ jsx30(PatentRenderShell, { ...props }),
5489
5755
  props.children
5490
5756
  ] }) });
5491
5757
  }
5492
- function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onChange, className }) {
5758
+ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onInterrupt, onChange, className }) {
5493
5759
  const ed = useEditor();
5494
- const rootRef = useRef4(null);
5760
+ const rootRef = useRef5(null);
5495
5761
  const [embedding, setEmbedding] = useState8(false);
5496
5762
  const { layout, update } = usePanelLayout();
5497
- const asideRef = useRef4(null);
5763
+ const asideRef = useRef5(null);
5498
5764
  useShortcuts(rootRef);
5499
5765
  useEffect4(() => {
5500
5766
  ed.setAgent(agentStatus);
5501
5767
  }, [agentStatus]);
5502
- const first = useRef4(true);
5768
+ const first = useRef5(true);
5503
5769
  useEffect4(() => {
5504
5770
  if (first.current) {
5505
5771
  first.current = false;
@@ -5507,6 +5773,17 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5507
5773
  }
5508
5774
  onChange?.(ed.state.doc);
5509
5775
  }, [ed.state.doc]);
5776
+ const running = agentStatus !== "idle";
5777
+ const [confirming, setConfirming] = useState8(null);
5778
+ const { interrupted, onInterrupted } = chat;
5779
+ const interruptedId = interrupted?.id;
5780
+ useEffect4(() => {
5781
+ if (interruptedId) update((l) => ({ chatOpen: true, chatHeight: Math.max(l.chatHeight, 180) }));
5782
+ }, [interruptedId, update]);
5783
+ const resolveInterrupted = (action) => {
5784
+ if (action === "restart" && interrupted?.drawn) setConfirming("restart");
5785
+ else onInterrupted?.(action);
5786
+ };
5510
5787
  const embed = async () => {
5511
5788
  if (!onEmbed || !ed.report.ok) return;
5512
5789
  setEmbedding(true);
@@ -5518,25 +5795,32 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5518
5795
  setEmbedding(false);
5519
5796
  }
5520
5797
  };
5521
- return /* @__PURE__ */ jsxs17(
5798
+ return /* @__PURE__ */ jsxs19(
5522
5799
  "div",
5523
5800
  {
5524
5801
  ref: rootRef,
5525
5802
  tabIndex: -1,
5526
5803
  onPointerDownCapture: (e) => {
5527
- if (!e.target.closest("input, textarea, select, button, [role=option]")) rootRef.current?.focus({ preventScroll: true });
5804
+ if (!e.target.closest("input, textarea, select, button, [role=option], [role=alertdialog]")) rootRef.current?.focus({ preventScroll: true });
5528
5805
  },
5529
- className: cn25("flex h-full min-h-[560px] w-full flex-col overflow-hidden bg-background text-foreground outline-none", className),
5806
+ className: cn25("relative flex h-full min-h-[560px] w-full flex-col overflow-hidden bg-background text-foreground outline-none", className),
5530
5807
  "data-slot": "patent-render",
5531
5808
  children: [
5532
- /* @__PURE__ */ jsx28(HeaderBar, { onEmbed: onEmbed ? embed : void 0, onCancel, embedding }),
5533
- /* @__PURE__ */ jsxs17("div", { className: "flex min-h-0 flex-1", children: [
5534
- /* @__PURE__ */ jsxs17("div", { className: "flex min-w-0 flex-1 flex-col", children: [
5535
- /* @__PURE__ */ jsxs17("div", { className: "relative min-h-0 flex-1", children: [
5536
- /* @__PURE__ */ jsx28(Canvas, {}),
5537
- /* @__PURE__ */ jsx28(Toolbox, { className: "absolute top-3 left-3" }),
5538
- /* @__PURE__ */ jsx28(SelectionBar, { className: "absolute top-3 left-1/2 -translate-x-1/2" }),
5539
- !layout.sideOpen && /* @__PURE__ */ jsx28(
5809
+ /* @__PURE__ */ jsx30(
5810
+ HeaderBar,
5811
+ {
5812
+ onEmbed: onEmbed ? embed : void 0,
5813
+ embedding,
5814
+ onCancel: onCancel ? () => running ? setConfirming("cancel") : onCancel() : void 0
5815
+ }
5816
+ ),
5817
+ /* @__PURE__ */ jsxs19("div", { className: "flex min-h-0 flex-1", children: [
5818
+ /* @__PURE__ */ jsxs19("div", { className: "flex min-w-0 flex-1 flex-col", children: [
5819
+ /* @__PURE__ */ jsxs19("div", { className: "relative min-h-0 flex-1", children: [
5820
+ /* @__PURE__ */ jsx30(Canvas, {}),
5821
+ /* @__PURE__ */ jsx30(Toolbox, { className: "absolute top-3 left-3" }),
5822
+ /* @__PURE__ */ jsx30(SelectionBar, { className: "absolute top-3 left-1/2 -translate-x-1/2" }),
5823
+ !layout.sideOpen && /* @__PURE__ */ jsx30(
5540
5824
  Button,
5541
5825
  {
5542
5826
  variant: "outline",
@@ -5544,11 +5828,11 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5544
5828
  className: "absolute top-3 right-3 size-8 bg-background/95 shadow-sm",
5545
5829
  "aria-label": "Show layers and inspector",
5546
5830
  onClick: () => update(() => ({ sideOpen: true })),
5547
- children: /* @__PURE__ */ jsx28(PanelRightOpen, {})
5831
+ children: /* @__PURE__ */ jsx30(PanelRightOpen, {})
5548
5832
  }
5549
5833
  )
5550
5834
  ] }),
5551
- /* @__PURE__ */ jsx28(
5835
+ /* @__PURE__ */ jsx30(
5552
5836
  ResizeHandle,
5553
5837
  {
5554
5838
  axis: "y",
@@ -5557,10 +5841,11 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5557
5841
  onToggle: () => update((l) => ({ chatOpen: !l.chatOpen }))
5558
5842
  }
5559
5843
  ),
5560
- /* @__PURE__ */ jsx28(
5844
+ /* @__PURE__ */ jsx30(
5561
5845
  ChatDock,
5562
5846
  {
5563
5847
  ...chat,
5848
+ onInterrupted: resolveInterrupted,
5564
5849
  status: agentStatus,
5565
5850
  selectionCount: ed.state.selection.length,
5566
5851
  historyHeight: layout.chatHeight,
@@ -5569,8 +5854,8 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5569
5854
  }
5570
5855
  )
5571
5856
  ] }),
5572
- layout.sideOpen && /* @__PURE__ */ jsxs17(Fragment6, { children: [
5573
- /* @__PURE__ */ jsx28(
5857
+ layout.sideOpen && /* @__PURE__ */ jsxs19(Fragment7, { children: [
5858
+ /* @__PURE__ */ jsx30(
5574
5859
  ResizeHandle,
5575
5860
  {
5576
5861
  axis: "x",
@@ -5579,10 +5864,10 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5579
5864
  onToggle: () => update(() => ({ sideOpen: false }))
5580
5865
  }
5581
5866
  ),
5582
- /* @__PURE__ */ jsxs17("aside", { ref: asideRef, className: "flex shrink-0 flex-col border-l bg-background", style: { width: layout.sideWidth }, children: [
5583
- /* @__PURE__ */ jsxs17("div", { className: "relative flex min-h-0 flex-col", style: { flex: `${layout.split} 1 0` }, children: [
5584
- /* @__PURE__ */ jsx28(LayersPanel, { className: "min-h-0 flex-1" }),
5585
- /* @__PURE__ */ jsx28(
5867
+ /* @__PURE__ */ jsxs19("aside", { ref: asideRef, className: "flex shrink-0 flex-col border-l bg-background", style: { width: layout.sideWidth }, children: [
5868
+ /* @__PURE__ */ jsxs19("div", { className: "relative flex min-h-0 flex-col", style: { flex: `${layout.split} 1 0` }, children: [
5869
+ /* @__PURE__ */ jsx30(LayersPanel, { className: "min-h-0 flex-1" }),
5870
+ /* @__PURE__ */ jsx30(
5586
5871
  Button,
5587
5872
  {
5588
5873
  variant: "ghost",
@@ -5590,11 +5875,11 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5590
5875
  className: "absolute top-1.5 right-9 size-6",
5591
5876
  "aria-label": "Hide side panel",
5592
5877
  onClick: () => update(() => ({ sideOpen: false })),
5593
- children: /* @__PURE__ */ jsx28(PanelRightClose, { className: "size-3.5" })
5878
+ children: /* @__PURE__ */ jsx30(PanelRightClose, { className: "size-3.5" })
5594
5879
  }
5595
5880
  )
5596
5881
  ] }),
5597
- /* @__PURE__ */ jsx28(
5882
+ /* @__PURE__ */ jsx30(
5598
5883
  ResizeHandle,
5599
5884
  {
5600
5885
  axis: "y",
@@ -5602,17 +5887,59 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5602
5887
  onDrag: (d) => update((l) => ({ split: l.split + d / Math.max(1, asideRef.current?.clientHeight ?? 600) }))
5603
5888
  }
5604
5889
  ),
5605
- /* @__PURE__ */ jsx28(Inspector, { className: "min-h-0 border-t", style: { flex: `${1 - layout.split} 1 0` } })
5890
+ /* @__PURE__ */ jsx30(Inspector, { className: "min-h-0 border-t", style: { flex: `${1 - layout.split} 1 0` } })
5606
5891
  ] })
5607
5892
  ] })
5608
- ] })
5893
+ ] }),
5894
+ /* @__PURE__ */ jsxs19(
5895
+ ConfirmDialog,
5896
+ {
5897
+ open: confirming === "cancel" && running,
5898
+ title: "Stop drawing and close?",
5899
+ confirmLabel: "Stop and close",
5900
+ cancelLabel: "Keep drawing",
5901
+ onCancel: () => setConfirming(null),
5902
+ onConfirm: () => {
5903
+ setConfirming(null);
5904
+ onInterrupt?.();
5905
+ onCancel?.();
5906
+ },
5907
+ children: [
5908
+ "The assistant is still drawing FIG. ",
5909
+ ed.state.doc.figureNumber,
5910
+ ".",
5911
+ " ",
5912
+ onChange ? "Finished steps are kept, and you can continue when you reopen this figure." : "Its unfinished work will be lost."
5913
+ ]
5914
+ }
5915
+ ),
5916
+ /* @__PURE__ */ jsxs19(
5917
+ ConfirmDialog,
5918
+ {
5919
+ open: confirming === "restart" && !!interrupted,
5920
+ title: "Start this drawing over?",
5921
+ safe: "confirm",
5922
+ destructive: true,
5923
+ confirmLabel: "Start over",
5924
+ cancelLabel: "Cancel",
5925
+ onCancel: () => setConfirming(null),
5926
+ onConfirm: () => {
5927
+ setConfirming(null);
5928
+ onInterrupted?.("restart");
5929
+ },
5930
+ children: [
5931
+ interrupted?.drawn === 1 ? "The 1 item drawn so far will be removed" : `The ${interrupted?.drawn ?? 0} items drawn so far will be removed`,
5932
+ ", and the assistant will draw your request again."
5933
+ ]
5934
+ }
5935
+ )
5609
5936
  ]
5610
5937
  }
5611
5938
  );
5612
5939
  }
5613
5940
  function useShortcuts(rootRef) {
5614
5941
  const ed = useEditor();
5615
- const edRef = useRef4(ed);
5942
+ const edRef = useRef5(ed);
5616
5943
  useEffect4(() => {
5617
5944
  edRef.current = ed;
5618
5945
  });
@@ -5621,7 +5948,7 @@ function useShortcuts(rootRef) {
5621
5948
  if (!root) return;
5622
5949
  const onKey = (e) => {
5623
5950
  const t = e.target;
5624
- if (t.closest("input, textarea, select, [contenteditable=true]")) return;
5951
+ if (t.closest("input, textarea, select, [contenteditable=true], [role=alertdialog]")) return;
5625
5952
  const ed2 = edRef.current;
5626
5953
  const { doc, selection } = ed2.state;
5627
5954
  const mod = e.metaKey || e.ctrlKey;
@@ -5688,9 +6015,79 @@ function useShortcuts(rootRef) {
5688
6015
  }
5689
6016
 
5690
6017
  // ../../src/patent-render/client/useAgentChat.ts
5691
- import { useCallback as useCallback4, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef5, useState as useState9 } from "react";
6018
+ import { useCallback as useCallback4, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef6, useState as useState9 } from "react";
5692
6019
  import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
5693
6020
 
6021
+ // ../../src/patent-render/schema/run.ts
6022
+ import { z as z4 } from "zod";
6023
+ var RunResume = z4.object({
6024
+ kind: z4.enum(["new", "edit"]),
6025
+ request: z4.string(),
6026
+ plan: FigurePlan.optional(),
6027
+ steps: z4.array(z4.string()).default([])
6028
+ });
6029
+ function isNewFigure(doc) {
6030
+ return doc.layers.every((l) => l.items.every((i) => i.type === "figLabel"));
6031
+ }
6032
+ function snapshotOf(doc) {
6033
+ const { jurisdiction, sheet, layers, numerals, lettering, view, explodeLines, sheetLabel } = doc;
6034
+ return { jurisdiction, sheet, layers, numerals, lettering, view, explodeLines, ...sheetLabel ? { sheetLabel } : {} };
6035
+ }
6036
+ function restorePatch(doc, to) {
6037
+ const patches = [
6038
+ ...doc.layers.map((l) => ({ op: "removeLayer", id: l.id })),
6039
+ ...to.layers.map((layer) => ({ op: "addLayer", layer })),
6040
+ ...Object.keys(doc.numerals).filter((n) => !(n in to.numerals)).map((n) => ({ op: "setNumeral", n, label: null })),
6041
+ ...Object.entries(to.numerals).filter(([n, label]) => doc.numerals[n] !== label).map(([n, label]) => ({ op: "setNumeral", n, label })),
6042
+ { op: "setSheet", sheet: to.sheet },
6043
+ { op: "setJurisdiction", jurisdiction: to.jurisdiction },
6044
+ { op: "setLettering", lettering: to.lettering },
6045
+ { op: "setView", view: to.view, explodeLines: to.explodeLines },
6046
+ { op: "setSheetLabel", sheetLabel: to.sheetLabel ?? null }
6047
+ ];
6048
+ return { op: "batch", patches };
6049
+ }
6050
+ function countEdits(patch) {
6051
+ return patch.op === "batch" ? patch.patches.reduce((n, p) => n + countEdits(p), 0) : 1;
6052
+ }
6053
+ function drawnSince(doc, before) {
6054
+ const had = new Set(before.layers.flatMap((l) => l.items.map((i) => i.id)));
6055
+ return doc.layers.flatMap((l) => l.items).filter((i) => !had.has(i.id)).length;
6056
+ }
6057
+ function repairTranscript(messages) {
6058
+ let changed = false;
6059
+ const out = [];
6060
+ const answered = new Set(messages.flatMap((m) => m.parts ?? []).filter((p) => p.type === "tool-result").map((p) => p.toolCallId));
6061
+ messages.forEach((message, index) => {
6062
+ const m = message;
6063
+ if (m.role !== "assistant" || !Array.isArray(m.parts)) {
6064
+ out.push(message);
6065
+ return;
6066
+ }
6067
+ const parts = m.parts.filter((p) => p.type !== "tool-call" || answered.has(p.id));
6068
+ if (parts.length !== m.parts.length || index === messages.length - 1) {
6069
+ while (parts.at(-1)?.type === "thinking") parts.pop();
6070
+ }
6071
+ if (parts.length === m.parts.length) {
6072
+ out.push(message);
6073
+ return;
6074
+ }
6075
+ changed = true;
6076
+ const useful = parts.some((p) => p.type === "tool-call" || p.type === "text" && String(p.content ?? "").trim());
6077
+ if (useful) out.push({ ...message, parts });
6078
+ });
6079
+ return changed ? out : messages;
6080
+ }
6081
+ function doneLabel(label) {
6082
+ return label.replace(/^Planning /, "Planned ").replace(/^Drawing (?=\S)/, "Drew ").replace(/^Reviewing /, "Reviewed ").replace(/^Applying /, "Applied ");
6083
+ }
6084
+ var MAX_STEPS = 6;
6085
+ function interruptionSteps(run) {
6086
+ const labels = run.steps.filter((s, i) => s.label !== "Drawing" || i === run.steps.length - 1);
6087
+ const all = labels.map((s) => s.status === "active" ? { label: `Stopped while ${s.label.charAt(0).toLowerCase()}${s.label.slice(1)}`, status: "stopped" } : { label: doneLabel(s.label), status: "done" });
6088
+ return { steps: all.slice(-MAX_STEPS), hidden: Math.max(0, all.length - MAX_STEPS) };
6089
+ }
6090
+
5694
6091
  // ../../src/patent-render/protocol.ts
5695
6092
  var EVENTS = {
5696
6093
  patch: "pr.patch",
@@ -5716,6 +6113,19 @@ function imageUrl(part) {
5716
6113
  if (s.type === "data") return `data:${s.mimeType ?? "image/png"};base64,${s.value}`;
5717
6114
  return null;
5718
6115
  }
6116
+ function messageAttachments(m) {
6117
+ if (m?.role !== "user") return [];
6118
+ return m.parts.flatMap((p, i) => {
6119
+ const url = p.type === "image" ? imageUrl(p) : null;
6120
+ return url ? [{ id: `${m.id}-${i}`, name: "attachment", url }] : [];
6121
+ });
6122
+ }
6123
+ function finishedRun(chunk) {
6124
+ const c = chunk;
6125
+ if (c.metadata?.tanstack?.model === "connect-wrapper") return false;
6126
+ const reason = c.finishReason ?? c.metadata?.tanstack?.finishReason;
6127
+ return reason === void 0 || reason === null || reason === "stop";
6128
+ }
5719
6129
  function friendlyError(e) {
5720
6130
  const status = /status:? (\d{3})/.exec(e.message)?.[1];
5721
6131
  if (status === "503") return "The drawing assistant isn't configured on the server yet (model API key missing). Manual editing still works.";
@@ -5723,32 +6133,60 @@ function friendlyError(e) {
5723
6133
  if (status === "400") return "The assistant couldn't read this figure. Try again; if it persists, reopen the editor.";
5724
6134
  if (status === "429") return "The assistant is busy (rate limited). Wait a moment and try again.";
5725
6135
  if (status && status.startsWith("5")) return "The assistant hit a server error. Changes made so far are kept; try again.";
6136
+ if (/terminated|network|failed to fetch|fetch failed|load failed|connection|aborted/i.test(e.message)) return "The connection to the assistant was lost. Changes made so far are kept.";
5726
6137
  return e.message || "The assistant hit an error. Changes made so far are kept.";
5727
6138
  }
6139
+ var FAILED_START_MS = 1500;
5728
6140
  function useAgentChat({ endpoint, context }) {
5729
6141
  const ed = useEditor();
5730
- const edRef = useRef5(ed);
6142
+ const edRef = useRef6(ed);
5731
6143
  useEffect5(() => {
5732
6144
  edRef.current = ed;
5733
6145
  });
5734
- const [meta, setMeta] = useState9({});
5735
- const [turn, setTurn] = useState9(0);
5736
- const turnRef = useRef5(0);
6146
+ const [initialChat] = useState9(() => repairTranscript(ed.state.doc.chat));
6147
+ const [turn, setTurn] = useState9(() => initialChat.filter((m) => m.role === "user").length);
6148
+ const turnRef = useRef6(turn);
6149
+ const [meta, setMeta] = useState9(() => {
6150
+ const plan = ed.state.doc.run?.plan;
6151
+ return plan ? { [turn]: { ...blankMeta(), plan } } : {};
6152
+ });
5737
6153
  const updateMeta = useCallback4((fn) => {
5738
6154
  const turn2 = turnRef.current;
5739
6155
  setMeta((all) => ({ ...all, [turn2]: fn(all[turn2] ?? blankMeta()) }));
5740
6156
  }, []);
6157
+ const [run, setRunState] = useState9(ed.state.doc.run ?? null);
6158
+ const runRef = useRef6(run);
6159
+ const setRun = useCallback4((next) => {
6160
+ runRef.current = next;
6161
+ setRunState(next);
6162
+ }, []);
6163
+ const updateRun = useCallback4((fn) => {
6164
+ if (runRef.current) setRun(fn(runRef.current));
6165
+ }, [setRun]);
6166
+ const addStep = useCallback4((label, status) => {
6167
+ updateRun((r) => ({ ...r, steps: [...r.steps.map((s) => ({ ...s, status: "done" })), { label, status }] }));
6168
+ }, [updateRun]);
6169
+ const [live, setLive] = useState9(false);
6170
+ const outcome = useRef6({ finished: false, stopped: false });
5741
6171
  const connection = useMemo4(() => fetchServerSentEvents(endpoint), [endpoint]);
5742
6172
  const chat = useChat({
5743
6173
  connection,
5744
6174
  threadId: ed.state.doc.id,
5745
- initialMessages: ed.state.doc.chat,
6175
+ initialMessages: initialChat,
6176
+ onChunk: (chunk) => {
6177
+ if (chunk.type === "RUN_FINISHED") outcome.current.finished = finishedRun(chunk);
6178
+ else if (chunk.type === "RUN_ERROR") outcome.current.finished = false;
6179
+ },
5746
6180
  onCustomEvent: (type, data) => {
5747
6181
  if (type === EVENTS.patch) {
5748
- edRef.current.apply(data.patch, { record: "agent" });
6182
+ const patch = data.patch;
6183
+ edRef.current.apply(patch, { record: "agent" });
5749
6184
  updateMeta((m) => ({ ...m, patches: m.patches + 1 }));
6185
+ updateRun((r) => ({ ...r, edits: r.edits + countEdits(patch) }));
5750
6186
  } else if (type === EVENTS.plan) {
5751
- updateMeta((m) => ({ ...m, plan: data.plan }));
6187
+ const { plan } = data;
6188
+ updateMeta((m) => ({ ...m, plan }));
6189
+ updateRun((r) => ({ ...r, plan }));
5752
6190
  } else if (type === EVENTS.status) {
5753
6191
  const s = data;
5754
6192
  updateMeta((m) => ({
@@ -5756,36 +6194,144 @@ function useAgentChat({ endpoint, context }) {
5756
6194
  phase: s.phase,
5757
6195
  steps: [...m.steps.map((x) => x.status === "active" ? { ...x, status: "done" } : x), { label: s.label, status: "active" }]
5758
6196
  }));
6197
+ addStep(s.label, "active");
5759
6198
  } else if (type === EVENTS.review) {
5760
6199
  const r = data;
6200
+ const label = r.verdict === "ok" ? `Review ${r.round}: looks good` : `Review ${r.round}: ${r.findings.length} fix${r.findings.length === 1 ? "" : "es"}`;
5761
6201
  updateMeta((m) => ({
5762
6202
  ...m,
5763
- steps: [
5764
- ...m.steps.map((x) => x.status === "active" ? { ...x, status: "done" } : x),
5765
- { label: r.verdict === "ok" ? `Review ${r.round}: looks good` : `Review ${r.round}: ${r.findings.length} fix${r.findings.length === 1 ? "" : "es"}`, status: "done" }
5766
- ]
6203
+ steps: [...m.steps.map((x) => x.status === "active" ? { ...x, status: "done" } : x), { label, status: "done" }]
5767
6204
  }));
6205
+ addStep(label, "done");
5768
6206
  }
5769
6207
  }
5770
6208
  });
5771
6209
  const running = chat.isLoading;
5772
6210
  const currentMeta = meta[turn];
5773
6211
  const agentStatus = running ? currentMeta?.phase ?? "drawing" : "idle";
5774
- const send = useCallback4(async (text, attachments, preferences) => {
5775
- const parts = (await Promise.all(attachments.map(fileToPart))).filter((p) => !!p);
5776
- const ed2 = edRef.current;
5777
- const next = chat.messages.filter((m) => m.role === "user").length + 1;
6212
+ const start = useCallback4(async (o) => {
6213
+ const id = newId("run");
6214
+ outcome.current = { finished: false, stopped: false };
6215
+ setRun({ ...o.record, id, chatLength: o.record.chatLength ?? o.messages.length });
6216
+ setLive(true);
6217
+ const next = o.messages.filter((m) => m.role === "user").length + 1;
5778
6218
  turnRef.current = next;
5779
6219
  setTurn(next);
5780
6220
  setMeta((all) => ({ ...all, [next]: blankMeta() }));
5781
- const body = { document: { ...ed2.state.doc, chat: [] }, selection: ed2.state.selection, context, preferences };
5782
- const content = parts.length ? { content: [...text ? [{ type: "text", content: text }] : [], ...parts] } : text;
5783
- await chat.sendMessage(content, { body });
5784
- }, [chat, context]);
6221
+ let failed = false;
6222
+ try {
6223
+ const parts = (await Promise.all(o.attachments.map(fileToPart))).filter((p) => !!p);
6224
+ if (o.messages !== chat.messages) chat.setMessages(o.messages);
6225
+ const body = {
6226
+ document: { ...o.doc, chat: [], run: void 0 },
6227
+ selection: o.record.selection,
6228
+ context,
6229
+ preferences: o.record.preferences,
6230
+ resume: o.resume
6231
+ };
6232
+ const content = parts.length ? { content: [...o.text ? [{ type: "text", content: o.text }] : [], ...parts] } : o.text;
6233
+ await chat.sendMessage(content, { body });
6234
+ } catch {
6235
+ failed = true;
6236
+ }
6237
+ const r = runRef.current;
6238
+ if (r?.id !== id) return;
6239
+ setLive(false);
6240
+ if (!failed && (outcome.current.finished || outcome.current.stopped)) {
6241
+ setRun(null);
6242
+ } else if (!o.resume && !r.steps.length && !r.edits) {
6243
+ setTimeout(() => {
6244
+ if (runRef.current?.id === id) setRun(null);
6245
+ }, FAILED_START_MS);
6246
+ }
6247
+ }, [chat, context, setRun]);
6248
+ const send = useCallback4(async (text, attachments, preferences) => {
6249
+ const { doc: doc2, selection } = edRef.current.state;
6250
+ await start({
6251
+ text,
6252
+ attachments,
6253
+ doc: doc2,
6254
+ messages: repairTranscript(chat.messages),
6255
+ record: { kind: isNewFigure(doc2) ? "new" : "edit", request: text, preferences, selection, steps: [], edits: 0, before: snapshotOf(doc2) }
6256
+ });
6257
+ }, [chat.messages, start]);
6258
+ const interruptedRun = run && !live && !running ? run : null;
6259
+ const doc = ed.state.doc;
6260
+ const interrupted = useMemo4(() => {
6261
+ const r = interruptedRun;
6262
+ if (!r) return null;
6263
+ const { steps, hidden } = interruptionSteps(r);
6264
+ return {
6265
+ id: r.id,
6266
+ request: r.request,
6267
+ steps,
6268
+ hiddenSteps: hidden,
6269
+ edits: r.edits,
6270
+ kind: r.kind === "edit" ? "edit" : r.plan || r.edits ? "drawing" : "planning",
6271
+ attachments: messageAttachments(chat.messages[r.chatLength]),
6272
+ drawn: drawnSince(doc, r.before)
6273
+ };
6274
+ }, [interruptedRun, chat.messages, doc]);
6275
+ const resolveInterrupted = useCallback4((action) => {
6276
+ const r = runRef.current;
6277
+ if (!r) return;
6278
+ const ed2 = edRef.current;
6279
+ const { doc: doc2 } = ed2.state;
6280
+ const transcript = repairTranscript(chat.messages);
6281
+ const beforeTurn = transcript.slice(0, r.chatLength);
6282
+ switch (action) {
6283
+ case "dismiss":
6284
+ setRun(null);
6285
+ return;
6286
+ case "edit":
6287
+ chat.setMessages(beforeTurn);
6288
+ setRun(null);
6289
+ return;
6290
+ case "undo":
6291
+ ed2.apply(restorePatch(doc2, r.before));
6292
+ setRun(null);
6293
+ return;
6294
+ case "continue": {
6295
+ const ids = new Set(doc2.layers.flatMap((l) => l.items.map((i) => i.id)));
6296
+ void start({
6297
+ text: r.kind === "edit" ? "Continue this change" : "Continue drawing",
6298
+ attachments: [],
6299
+ doc: doc2,
6300
+ messages: transcript,
6301
+ record: { ...r, selection: r.selection.filter((i) => ids.has(i)), steps: r.steps.map((s) => ({ ...s, status: "done" })) },
6302
+ resume: { kind: r.kind, request: r.request, plan: r.plan, steps: r.steps.map((s) => s.label) }
6303
+ });
6304
+ return;
6305
+ }
6306
+ case "retry":
6307
+ case "restart": {
6308
+ const patch = restorePatch(doc2, r.before);
6309
+ const reset = r.edits > 0 || action === "restart";
6310
+ const clean = reset ? applyPatch(doc2, patch).doc : doc2;
6311
+ if (reset) ed2.apply(patch);
6312
+ void start({
6313
+ text: r.request,
6314
+ attachments: messageAttachments(chat.messages[r.chatLength]),
6315
+ doc: clean,
6316
+ messages: beforeTurn,
6317
+ record: { kind: r.kind, request: r.request, preferences: r.preferences, selection: r.selection, before: r.before, steps: [], edits: 0, plan: void 0 }
6318
+ });
6319
+ return;
6320
+ }
6321
+ }
6322
+ }, [chat, setRun, start]);
6323
+ const stop = useCallback4(() => {
6324
+ outcome.current.stopped = true;
6325
+ chat.stop();
6326
+ }, [chat]);
6327
+ const interrupt = useCallback4(() => {
6328
+ chat.stop();
6329
+ }, [chat]);
5785
6330
  const messages = useMemo4(() => {
5786
6331
  const out = [];
5787
6332
  let t = 0;
5788
6333
  let metaShownFor = -1;
6334
+ let editsShownFor = -1;
5789
6335
  for (const m of chat.messages) {
5790
6336
  if (m.role === "user") {
5791
6337
  t += 1;
@@ -5809,7 +6355,8 @@ function useAgentChat({ endpoint, context }) {
5809
6355
  if (steps.length) parts.push({ type: "progress", steps });
5810
6356
  }
5811
6357
  for (const p of m.parts) if (p.type === "text" && p.content.trim()) parts.push({ type: "text", text: p.content });
5812
- if (rm && !rm.plan && rm.patches && !(running && t === turn) && metaShownFor === t && !parts.some((p) => p.type === "edits")) {
6358
+ if (rm && !rm.plan && rm.patches && !(running && t === turn) && metaShownFor === t && editsShownFor !== t) {
6359
+ editsShownFor = t;
5813
6360
  parts.push({ type: "edits", summary: "Updated the drawing", count: rm.patches });
5814
6361
  }
5815
6362
  if (parts.length) out.push({ id: m.id, role: "assistant", parts });
@@ -5818,11 +6365,11 @@ function useAgentChat({ endpoint, context }) {
5818
6365
  if (chat.error) out.push({ id: "error", role: "assistant", parts: [{ type: "error", message: friendlyError(chat.error) }] });
5819
6366
  return out;
5820
6367
  }, [chat.messages, chat.error, meta, running, turn]);
5821
- return { messages, send, stop: chat.stop, agentStatus, rawMessages: chat.messages };
6368
+ return { messages, send, stop, interrupt, agentStatus, rawMessages: chat.messages, run, interrupted, resolveInterrupted };
5822
6369
  }
5823
6370
 
5824
6371
  // ../../src/patent-render/client/PatentRender.tsx
5825
- import { jsx as jsx29 } from "react/jsx-runtime";
6372
+ import { jsx as jsx31 } from "react/jsx-runtime";
5826
6373
  function PatentRender(props) {
5827
6374
  const { document: document2, figureNumber, jurisdiction, context, sheetLabel } = props;
5828
6375
  const initial = useMemo5(
@@ -5839,32 +6386,79 @@ function PatentRender(props) {
5839
6386
  // eslint-disable-next-line react-hooks/exhaustive-deps
5840
6387
  []
5841
6388
  );
5842
- return /* @__PURE__ */ jsx29(TooltipProvider, { delayDuration: 400, children: /* @__PURE__ */ jsx29(EditorProvider, { doc: initial, children: /* @__PURE__ */ jsx29(AgentShell, { ...props }) }) });
6389
+ return /* @__PURE__ */ jsx31(TooltipProvider, { delayDuration: 400, children: /* @__PURE__ */ jsx31(EditorProvider, { doc: initial, children: /* @__PURE__ */ jsx31(AgentShell, { ...props }) }) });
5843
6390
  }
5844
- function AgentShell({ endpoint, context, onEmbed, onCancel, onChange, exportPng, className }) {
6391
+ function AgentShell({ endpoint, context, onEmbed, onCancel, onChange, onBusyChange, exportPng, className }) {
5845
6392
  const ed = useEditor();
5846
6393
  const agent = useAgentChat({ endpoint, context });
5847
- const chatRef = useRef6(agent.rawMessages);
6394
+ const busy = agent.agentStatus !== "idle";
6395
+ const latest = useRef7({ chat: agent.rawMessages, run: agent.run, doc: ed.state.doc, onChange });
6396
+ useLayoutEffect3(() => {
6397
+ latest.current = { chat: agent.rawMessages, run: agent.run, doc: ed.state.doc, onChange };
6398
+ });
6399
+ const unsaved = useRef7(false);
6400
+ const withSession = (doc) => {
6401
+ const next = { ...doc, chat: latest.current.chat };
6402
+ if (latest.current.run) next.run = latest.current.run;
6403
+ else delete next.run;
6404
+ return next;
6405
+ };
6406
+ const save = (doc, reason) => {
6407
+ unsaved.current = reason === "edit";
6408
+ latest.current.onChange?.(withSession(doc), { reason });
6409
+ };
6410
+ const { run } = agent;
6411
+ const runKey = run ? `${run.id}:${run.steps.length}:${run.plan ? 1 : 0}` : "";
6412
+ const first = useRef7(true);
5848
6413
  useEffect6(() => {
5849
- chatRef.current = agent.rawMessages;
5850
- }, [agent.rawMessages]);
5851
- const withChat = (doc) => ({ ...doc, chat: chatRef.current });
5852
- const wasRunning = useRef6(false);
6414
+ if (first.current) {
6415
+ first.current = false;
6416
+ return;
6417
+ }
6418
+ save(latest.current.doc, "run");
6419
+ }, [runKey, busy]);
5853
6420
  useEffect6(() => {
5854
- const running = agent.agentStatus !== "idle";
5855
- if (wasRunning.current && !running) onChange?.(withChat(ed.state.doc));
5856
- wasRunning.current = running;
5857
- }, [agent.agentStatus]);
5858
- return /* @__PURE__ */ jsx29(
6421
+ const onHide = () => {
6422
+ if (unsaved.current || latest.current.run) save(latest.current.doc, "close");
6423
+ };
6424
+ window.addEventListener("pagehide", onHide);
6425
+ return () => window.removeEventListener("pagehide", onHide);
6426
+ }, []);
6427
+ useEffect6(() => {
6428
+ if (!busy) return;
6429
+ const warn = (e) => {
6430
+ e.preventDefault();
6431
+ e.returnValue = "";
6432
+ };
6433
+ window.addEventListener("beforeunload", warn);
6434
+ return () => window.removeEventListener("beforeunload", warn);
6435
+ }, [busy]);
6436
+ const busyCallback = useRef7(onBusyChange);
6437
+ useLayoutEffect3(() => {
6438
+ busyCallback.current = onBusyChange;
6439
+ });
6440
+ useEffect6(() => {
6441
+ if (!busy) return;
6442
+ busyCallback.current?.(true);
6443
+ return () => busyCallback.current?.(false);
6444
+ }, [busy]);
6445
+ return /* @__PURE__ */ jsx31(
5859
6446
  PatentRenderShell,
5860
6447
  {
5861
6448
  className,
5862
6449
  agentStatus: agent.agentStatus,
5863
- chat: { messages: agent.messages, onSend: agent.send, onStop: agent.stop },
6450
+ chat: {
6451
+ messages: agent.messages,
6452
+ onSend: agent.send,
6453
+ onStop: agent.stop,
6454
+ interrupted: agent.interrupted,
6455
+ onInterrupted: agent.resolveInterrupted
6456
+ },
6457
+ onInterrupt: agent.interrupt,
5864
6458
  onCancel,
5865
- onChange: onChange ? (doc) => onChange(withChat(doc)) : void 0,
6459
+ onChange: onChange ? (doc) => save(doc, "edit") : void 0,
5866
6460
  onEmbed: async (r) => {
5867
- const document2 = withChat(r.document);
6461
+ const document2 = withSession(r.document);
5868
6462
  const png = exportPng ? (await exportPng(document2)).dataUrl : void 0;
5869
6463
  await onEmbed({ ...r, document: document2, png });
5870
6464
  }