dsh-codex-subscription 3.0.0 → 3.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/lib/client.js CHANGED
@@ -165,6 +165,147 @@ window.__ModuleLoader__.load({
165
165
  y: a.y + .15
166
166
  }];
167
167
  }
168
+ const finite$1 = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
169
+ const FILLABLE = [
170
+ "rectangle",
171
+ "circle",
172
+ "polygon",
173
+ "bezier"
174
+ ];
175
+ function normalizeBlur(value) {
176
+ if (value === void 0 || value === null) return void 0;
177
+ if (!finite$1(value, 0, 64)) throw Error(`blur must be 0–64 canvas pixels`);
178
+ return value >= .5 ? Math.round(value * 10) / 10 : void 0;
179
+ }
180
+ function normalizeGradient(gradient) {
181
+ if (gradient === void 0 || gradient === null) return void 0;
182
+ if (!gradient || typeof gradient !== "object") throw Error("Invalid gradient");
183
+ if (gradient.type === "none") return void 0;
184
+ if (gradient.type !== "linear" && gradient.type !== "radial") throw Error("gradient.type must be linear or radial");
185
+ const stops = gradient.stops;
186
+ if (!Array.isArray(stops) || stops.length < 2 || stops.length > 8) throw Error("gradient needs 2–8 stops");
187
+ const clean = stops.map((stop) => {
188
+ if (!stop || !finite$1(stop.offset, 0, 1) || !/^#[0-9a-f]{6}$/i.test(stop.color ?? "") || stop.opacity !== void 0 && !finite$1(stop.opacity, 0, 1)) throw Error("Each gradient stop needs offset 0–1 and color #rrggbb (optional opacity 0–1)");
189
+ return {
190
+ offset: stop.offset,
191
+ color: stop.color.toLowerCase(),
192
+ ...stop.opacity !== void 0 && stop.opacity < 1 ? { opacity: stop.opacity } : {}
193
+ };
194
+ }).sort((a, b) => a.offset - b.offset);
195
+ const number = (name, fallback, min = -8, max = 8) => {
196
+ const value = gradient[name] ?? fallback;
197
+ if (!finite$1(value, min, max)) throw Error(`gradient.${name} must be a number`);
198
+ return Math.round(value * 1e4) / 1e4;
199
+ };
200
+ if (gradient.type === "linear") return {
201
+ type: "linear",
202
+ x1: number("x1", 0),
203
+ y1: number("y1", 0),
204
+ x2: number("x2", 0),
205
+ y2: number("y2", 1),
206
+ stops: clean
207
+ };
208
+ const cx = number("cx", .5), cy = number("cy", .5), r = number("r", .5, 1e-4), ry = gradient.ry === void 0 ? r : number("ry", .5, 1e-4);
209
+ return {
210
+ type: "radial",
211
+ cx,
212
+ cy,
213
+ r,
214
+ ...ry !== r ? { ry } : {},
215
+ fx: number("fx", cx),
216
+ fy: number("fy", cy),
217
+ stops: clean
218
+ };
219
+ }
220
+ function gradientFits(shape, fill) {
221
+ return fill === true && FILLABLE.includes(shape);
222
+ }
223
+ const rgba = (color, opacity = 1) => {
224
+ const value = Number.parseInt(color.slice(1), 16);
225
+ return `rgba(${value >> 16 & 255},${value >> 8 & 255},${value & 255},${opacity})`;
226
+ };
227
+ function fillSketchShape(context, stroke, size, height) {
228
+ const gradient = stroke.gradient;
229
+ const xs = stroke.points.map((point) => point.x), ys = stroke.points.map((point) => point.y);
230
+ const x = Math.min(...xs) * size, y = Math.min(...ys) * height;
231
+ const w = (Math.max(...xs) - Math.min(...xs)) * size, h = (Math.max(...ys) - Math.min(...ys)) * height;
232
+ if (!gradient || !(w > 0 && h > 0) || !context.createLinearGradient) {
233
+ context.fill();
234
+ return;
235
+ }
236
+ let paint;
237
+ if (gradient.type === "linear") {
238
+ paint = context.createLinearGradient(x + gradient.x1 * w, y + gradient.y1 * h, x + gradient.x2 * w, y + gradient.y2 * h);
239
+ for (const stop of gradient.stops) paint.addColorStop(stop.offset, rgba(stop.color, stop.opacity));
240
+ context.fillStyle = paint;
241
+ context.fill();
242
+ return;
243
+ }
244
+ const rx = gradient.r * w, ry = (gradient.ry ?? gradient.r) * h;
245
+ paint = context.createRadialGradient((gradient.fx - gradient.cx) / gradient.r, (gradient.fy - gradient.cy) / (gradient.ry ?? gradient.r), 0, 0, 0, 1);
246
+ for (const stop of gradient.stops) paint.addColorStop(stop.offset, rgba(stop.color, stop.opacity));
247
+ context.save();
248
+ context.translate(x + gradient.cx * w, y + gradient.cy * h);
249
+ context.scale(rx, ry);
250
+ context.fillStyle = paint;
251
+ context.fill();
252
+ context.restore();
253
+ }
254
+ const BLEND_MODES = [
255
+ "multiply",
256
+ "screen",
257
+ "overlay",
258
+ "soft-light",
259
+ "hard-light",
260
+ "color-dodge",
261
+ "color-burn",
262
+ "darken",
263
+ "lighten",
264
+ "lighter"
265
+ ];
266
+ function normalizeBlend(value) {
267
+ if (value === void 0 || value === null || value === "normal") return void 0;
268
+ if (!BLEND_MODES.includes(value)) throw Error("blend must be one of normal, " + BLEND_MODES.join(", "));
269
+ return value;
270
+ }
271
+ function normalizeClip(clip) {
272
+ if (clip === void 0 || clip === null) return void 0;
273
+ if (!clip || typeof clip !== "object") throw Error("Invalid clip");
274
+ if (clip.shape === "none") return void 0;
275
+ const { shape, points } = clip;
276
+ if (![
277
+ "polygon",
278
+ "bezier",
279
+ "rectangle",
280
+ "circle"
281
+ ].includes(shape)) throw Error("clip.shape must be polygon, bezier, rectangle or circle");
282
+ if (!Array.isArray(points) || points.some((point) => !point || !finite$1(point.x, 0, 1) || !finite$1(point.y, 0, 1))) throw Error("clip.points must be {x,y} pairs inside 0..1");
283
+ if ((shape === "rectangle" || shape === "circle") && points.length !== 2) throw Error("clip rectangle and circle need exactly two opposite corners");
284
+ if (shape === "polygon" && (points.length < 3 || points.length > 2e3)) throw Error("clip polygon needs 3–2000 points");
285
+ if (shape === "bezier" && (points.length < 4 || points.length > 193 || (points.length - 1) % 3 !== 0)) throw Error("clip bezier needs 4, 7, ... 193 points (start + control1/control2/end per segment)");
286
+ return {
287
+ shape,
288
+ points: points.map((point) => ({
289
+ x: Math.round(point.x * 1e5) / 1e5,
290
+ y: Math.round(point.y * 1e5) / 1e5
291
+ }))
292
+ };
293
+ }
294
+ function applySketchClip(context, clip, size, height) {
295
+ const { shape, points } = clip;
296
+ const first = points[0], last = points.at(-1);
297
+ context.beginPath();
298
+ if (shape === "bezier") {
299
+ context.moveTo(first.x * size, first.y * height);
300
+ for (let i = 1; i < points.length; i += 3) context.bezierCurveTo(points[i].x * size, points[i].y * height, points[i + 1].x * size, points[i + 1].y * height, points[i + 2].x * size, points[i + 2].y * height);
301
+ } else if (shape === "polygon") {
302
+ context.moveTo(first.x * size, first.y * height);
303
+ for (const point of points.slice(1)) context.lineTo(point.x * size, point.y * height);
304
+ } else if (shape === "rectangle") context.rect(first.x * size, first.y * height, (last.x - first.x) * size, (last.y - first.y) * height);
305
+ else context.ellipse((first.x + last.x) * size / 2, (first.y + last.y) * height / 2, Math.abs(last.x - first.x) * size / 2, Math.abs(last.y - first.y) * height / 2, 0, 0, Math.PI * 2);
306
+ context.closePath();
307
+ context.clip();
308
+ }
168
309
  //#endregion
169
310
  //#region src/sketch-document.js
170
311
  const SKETCH_SIZE = 1024;
@@ -190,8 +331,13 @@ window.__ModuleLoader__.load({
190
331
  const stroke = strokes[index];
191
332
  const first = stroke.points[0];
192
333
  if (!first) continue;
193
- context.globalCompositeOperation = stroke.shape === "eraser" ? "destination-out" : "source-over";
334
+ context.globalCompositeOperation = stroke.shape === "eraser" ? "destination-out" : stroke.blend ?? "source-over";
194
335
  configureSketchBrush(context, stroke);
336
+ if (stroke.blur > 0) context.filter = `blur(${stroke.blur}px)`;
337
+ if (stroke.clip) {
338
+ context.save();
339
+ applySketchClip(context, stroke.clip, size, height);
340
+ }
195
341
  context.beginPath();
196
342
  const last = stroke.points.at(-1);
197
343
  if (stroke.shape === "text") {
@@ -218,7 +364,7 @@ window.__ModuleLoader__.load({
218
364
  }
219
365
  if (stroke.fill) {
220
366
  context.closePath();
221
- context.fill();
367
+ fillSketchShape(context, stroke, size, height);
222
368
  } else context.stroke();
223
369
  } else if (stroke.shape === "line") {
224
370
  context.moveTo(first.x * size, first.y * height);
@@ -226,17 +372,17 @@ window.__ModuleLoader__.load({
226
372
  context.stroke();
227
373
  } else if (stroke.shape === "rectangle") {
228
374
  context.rect(first.x * size, first.y * height, (last.x - first.x) * size, (last.y - first.y) * height);
229
- if (stroke.fill) context.fill();
375
+ if (stroke.fill) fillSketchShape(context, stroke, size, height);
230
376
  else context.stroke();
231
377
  } else if (stroke.shape === "circle") {
232
378
  context.ellipse((first.x + last.x) * size / 2, (first.y + last.y) * height / 2, Math.abs(last.x - first.x) * size / 2, Math.abs(last.y - first.y) * height / 2, 0, 0, Math.PI * 2);
233
- if (stroke.fill) context.fill();
379
+ if (stroke.fill) fillSketchShape(context, stroke, size, height);
234
380
  else context.stroke();
235
381
  } else if (stroke.shape === "polygon") {
236
382
  context.moveTo(first.x * size, first.y * height);
237
383
  for (const point of stroke.points.slice(1)) context.lineTo(point.x * size, point.y * height);
238
384
  context.closePath();
239
- if (stroke.fill) context.fill();
385
+ if (stroke.fill) fillSketchShape(context, stroke, size, height);
240
386
  else context.stroke();
241
387
  } else if (stroke.points.length === 1) {
242
388
  if (stroke.brushVersion === 2 && stroke.brush === "marker") context.rect(first.x * size - context.lineWidth / 2, first.y * height - context.lineWidth / 4, context.lineWidth, context.lineWidth / 2);
@@ -252,6 +398,8 @@ window.__ModuleLoader__.load({
252
398
  context.lineTo(last.x * size, last.y * height);
253
399
  context.stroke();
254
400
  }
401
+ if (stroke.clip) context.restore();
402
+ if (stroke.blur > 0) context.filter = "none";
255
403
  }
256
404
  context.globalCompositeOperation = "source-over";
257
405
  context.globalAlpha = 1;
@@ -316,7 +464,14 @@ window.__ModuleLoader__.load({
316
464
  ...layer,
317
465
  name: String(value).trim().slice(0, 40)
318
466
  };
319
- else if (action === "clear") layers[index] = {
467
+ else if (action === "blend") {
468
+ const blend = normalizeBlend(value);
469
+ const { blend: _old, ...rest } = layer;
470
+ layers[index] = blend ? {
471
+ ...rest,
472
+ blend
473
+ } : rest;
474
+ } else if (action === "clear") layers[index] = {
320
475
  ...layer,
321
476
  strokes: [],
322
477
  image: void 0
@@ -428,6 +583,7 @@ window.__ModuleLoader__.load({
428
583
  undo: ref([]),
429
584
  redo: ref([]),
430
585
  images: ref(/* @__PURE__ */ new Map()),
586
+ timeline: ref([]),
431
587
  saved: ref(null),
432
588
  dirty: ref(false),
433
589
  documentId: ref(crypto.randomUUID()),
@@ -1090,6 +1246,11 @@ window.__ModuleLoader__.load({
1090
1246
  "runtime/cancel",
1091
1247
  "storage/status",
1092
1248
  "storage/clear-forecast",
1249
+ "voice/start",
1250
+ "voice/stop",
1251
+ "voice/status",
1252
+ "voice/preview",
1253
+ "voice/catalog",
1093
1254
  "remote/status",
1094
1255
  "remote/enable",
1095
1256
  "remote/disable",
@@ -2169,9 +2330,18 @@ window.__ModuleLoader__.load({
2169
2330
  y: box.y + (p.y - box.y) * scaleY + dy
2170
2331
  }));
2171
2332
  if (points.some((p) => p.x < 0 || p.x > 1 || p.y < 0 || p.y > 1)) throw Error("Object would leave the canvas");
2333
+ const clip = stroke.clip && {
2334
+ ...stroke.clip,
2335
+ points: stroke.clip.points.map((p) => ({
2336
+ x: box.x + (p.x - box.x) * scaleX + dx,
2337
+ y: box.y + (p.y - box.y) * scaleY + dy
2338
+ }))
2339
+ };
2340
+ if (clip && clip.points.some((p) => p.x < 0 || p.x > 1 || p.y < 0 || p.y > 1)) throw Error("Object clip would leave the canvas");
2172
2341
  return {
2173
2342
  ...stroke,
2174
- points
2343
+ points,
2344
+ ...clip ? { clip } : {}
2175
2345
  };
2176
2346
  }
2177
2347
  function sketchObjectSummary(doc) {
@@ -2531,8 +2701,6 @@ window.__ModuleLoader__.load({
2531
2701
  "tspan",
2532
2702
  "image",
2533
2703
  "foreignObject",
2534
- "filter",
2535
- "clipPath",
2536
2704
  "mask",
2537
2705
  "pattern",
2538
2706
  "style",
@@ -2546,9 +2714,23 @@ window.__ModuleLoader__.load({
2546
2714
  "desc",
2547
2715
  "metadata",
2548
2716
  "defs",
2717
+ "clipPath",
2549
2718
  "linearGradient",
2550
2719
  "radialGradient",
2551
2720
  "stop",
2721
+ "filter",
2722
+ "feGaussianBlur",
2723
+ "feDropShadow",
2724
+ "feOffset",
2725
+ "feColorMatrix",
2726
+ "feFlood",
2727
+ "feComposite",
2728
+ "feMerge",
2729
+ "feMergeNode",
2730
+ "feBlend",
2731
+ "feMorphology",
2732
+ "feTurbulence",
2733
+ "feComponentTransfer",
2552
2734
  "namedview",
2553
2735
  "sodipodi:namedview"
2554
2736
  ]);
@@ -2672,7 +2854,7 @@ window.__ModuleLoader__.load({
2672
2854
  }
2673
2855
  return matrix;
2674
2856
  }
2675
- function parseColor(value) {
2857
+ function parseColor$1(value) {
2676
2858
  const text = String(value ?? "").trim().toLowerCase();
2677
2859
  if (!text || text === "none") return "none";
2678
2860
  if (text === "currentcolor") return "#000000";
@@ -2705,7 +2887,10 @@ window.__ModuleLoader__.load({
2705
2887
  fillOpacity: number("fill-opacity", parent.fillOpacity),
2706
2888
  strokeOpacity: number("stroke-opacity", parent.strokeOpacity),
2707
2889
  opacity: parent.opacity * number("opacity", 1),
2708
- display: own.display === "none" || own.visibility === "hidden" ? "none" : "inline"
2890
+ display: own.display === "none" || own.visibility === "hidden" ? "none" : "inline",
2891
+ blur: parent.blur ?? 0,
2892
+ blend: own["mix-blend-mode"] === void 0 ? parent.blend : own["mix-blend-mode"] === "normal" ? void 0 : own["mix-blend-mode"],
2893
+ clip: parent.clip
2709
2894
  };
2710
2895
  }
2711
2896
  function arcToCubics(x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
@@ -3029,12 +3214,43 @@ window.__ModuleLoader__.load({
3029
3214
  y: clamp((ty - originY) / viewHeight)
3030
3215
  };
3031
3216
  };
3032
- const gradientColor = (reference) => {
3217
+ const gradientNode = (reference) => {
3033
3218
  const target = byId.get(/^url\(\s*['"]?#([^)'"]+)['"]?\s*\)/.exec(reference)?.[1] ?? "");
3034
3219
  if (!target || !/Gradient$/.test(target.name)) throw Error(`SVG paint ${reference} does not reference a gradient defined in the same SVG`);
3035
- const stops = target.children.filter((child) => child.name === "stop");
3036
- if (!stops.length) throw Error(`Gradient ${target.attrs.id} has no stops`);
3037
- const channels = stops.map((stop) => parseColor(stop.attrs["stop-color"] ?? /stop-color\s*:\s*([^;]+)/.exec(stop.attrs.style ?? "")?.[1] ?? "#000000")).filter((color) => color !== "none").map((color) => [
3220
+ return target;
3221
+ };
3222
+ const gradientChain = (target) => {
3223
+ const chain = [target];
3224
+ for (let node = target; chain.length < 5;) {
3225
+ const href = node.attrs.href ?? node.attrs["xlink:href"];
3226
+ node = href?.startsWith("#") ? byId.get(href.slice(1)) : void 0;
3227
+ if (!node || !/Gradient$/.test(node.name)) break;
3228
+ chain.push(node);
3229
+ }
3230
+ return chain;
3231
+ };
3232
+ const gradientStops = (target) => {
3233
+ const holder = gradientChain(target).find((node) => node.children.some((child) => child.name === "stop"));
3234
+ if (!holder) throw Error(`Gradient ${target.attrs.id} has no stops`);
3235
+ let last = 0;
3236
+ return holder.children.filter((child) => child.name === "stop").map((stop) => {
3237
+ const css = (name) => stop.attrs[name] ?? new RegExp(name + "\\s*:\\s*([^;]+)").exec(stop.attrs.style ?? "")?.[1];
3238
+ const raw = String(stop.attrs.offset ?? "0").trim();
3239
+ const offset = Math.max(last, Math.min(1, raw.endsWith("%") ? Number.parseFloat(raw) / 100 : Number.parseFloat(raw) || 0));
3240
+ last = offset;
3241
+ const opacity = Number.parseFloat(css("stop-opacity") ?? "1");
3242
+ return {
3243
+ offset,
3244
+ color: parseColor$1(css("stop-color") ?? "#000000"),
3245
+ opacity: Number.isFinite(opacity) ? Math.max(0, Math.min(1, opacity)) : 1
3246
+ };
3247
+ }).filter((stop) => stop.color !== "none");
3248
+ };
3249
+ const averageColor = (reference, warn) => {
3250
+ const target = gradientNode(reference);
3251
+ const colors = gradientStops(target).map((stop) => stop.color);
3252
+ if (!colors.length) throw Error(`Gradient ${target.attrs.id} has no usable stops`);
3253
+ const channels = colors.map((color) => [
3038
3254
  1,
3039
3255
  3,
3040
3256
  5
@@ -3044,18 +3260,82 @@ window.__ModuleLoader__.load({
3044
3260
  1,
3045
3261
  2
3046
3262
  ].map((channel) => Math.round(channels.reduce((sum, item) => sum + item[channel], 0) / channels.length));
3047
- warnings.add(`Gradient ${target.attrs.id} was flattened to its average color; stack several bands for a real gradient.`);
3263
+ if (warn) warnings.add(`Gradient ${target.attrs.id} was flattened to its average color (a gradient on a stroke line, or on a path that had to be split).`);
3048
3264
  return `#${mean.map((value) => value.toString(16).padStart(2, "0")).join("")}`;
3049
3265
  };
3050
- const paint = (value) => String(value).startsWith("url(") ? gradientColor(value) : parseColor(value);
3266
+ const determinant = (m) => Math.abs(m[0] * m[3] - m[1] * m[2]);
3267
+ const nativeGradient = (reference, matrix, command) => {
3268
+ const target = gradientNode(reference);
3269
+ const chain = gradientChain(target);
3270
+ const attr = (name) => chain.find((node) => node.attrs[name] !== void 0)?.attrs[name];
3271
+ const stops = gradientStops(target);
3272
+ if (stops.length < 2) return void 0;
3273
+ const radial = target.name === "radialGradient";
3274
+ const objectBox = (attr("gradientUnits") ?? "objectBoundingBox") === "objectBoundingBox";
3275
+ const xs = command.points.map((point) => point.x), ys = command.points.map((point) => point.y);
3276
+ const bx = Math.min(...xs), by = Math.min(...ys), bw = Math.max(...xs) - bx, bh = Math.max(...ys) - by;
3277
+ if (!(bw > 1e-4 && bh > 1e-4)) return void 0;
3278
+ const gt = parseTransform(attr("gradientTransform"));
3279
+ const length = (name, fraction, axis) => {
3280
+ const raw = String(attr(name) ?? `${fraction * 100}%`).trim();
3281
+ if (!raw.endsWith("%")) return Number.parseFloat(raw) || 0;
3282
+ const part = Number.parseFloat(raw) / 100;
3283
+ return objectBox ? part : part * (axis === "x" ? viewWidth : axis === "y" ? viewHeight : Math.hypot(viewWidth, viewHeight) / Math.SQRT2);
3284
+ };
3285
+ const full = objectBox ? gt : multiply(matrix, gt);
3286
+ const place = (x, y) => {
3287
+ const [px, py] = apply$1(full, x, y);
3288
+ return objectBox ? [px, py] : [((px - originX) / viewWidth - bx) / bw, ((py - originY) / viewHeight - by) / bh];
3289
+ };
3290
+ const colors = stops.map((stop) => ({
3291
+ offset: stop.offset,
3292
+ color: stop.color,
3293
+ opacity: stop.opacity
3294
+ }));
3295
+ if (!radial) {
3296
+ const [x1, y1] = place(length("x1", 0, "x"), length("y1", 0, "y"));
3297
+ const [x2, y2] = place(length("x2", 1, "x"), length("y2", 0, "y"));
3298
+ return normalizeGradient({
3299
+ type: "linear",
3300
+ x1,
3301
+ y1,
3302
+ x2,
3303
+ y2,
3304
+ stops: colors
3305
+ });
3306
+ }
3307
+ const cx0 = length("cx", .5, "x"), cy0 = length("cy", .5, "y"), r0 = length("r", .5, "r");
3308
+ const [cx, cy] = place(cx0, cy0);
3309
+ const [fx, fy] = place(attr("fx") === void 0 ? cx0 : length("fx", .5, "x"), attr("fy") === void 0 ? cy0 : length("fy", .5, "y"));
3310
+ const k = Math.sqrt(determinant(full));
3311
+ return normalizeGradient({
3312
+ type: "radial",
3313
+ cx,
3314
+ cy,
3315
+ r: objectBox ? r0 * k : r0 * k / viewWidth / bw,
3316
+ ry: objectBox ? r0 * k : r0 * k / viewHeight / bh,
3317
+ fx,
3318
+ fy,
3319
+ stops: colors
3320
+ });
3321
+ };
3322
+ const paint = (value) => String(value).startsWith("url(") ? averageColor(value, false) : parseColor$1(value);
3051
3323
  const emit = (subpath, matrix, style, id) => {
3052
3324
  [subpath.start, ...subpath.curves.flatMap((curve) => [
3053
3325
  [curve[0], curve[1]],
3054
3326
  [curve[2], curve[3]],
3055
3327
  [curve[4], curve[5]]
3056
3328
  ])];
3329
+ const fillGradient = String(style.fill).startsWith("url(");
3057
3330
  const fill = style.fill === "none" ? "none" : paint(style.fill);
3058
- const stroke = style.stroke === "none" ? "none" : paint(style.stroke);
3331
+ const stroke = style.stroke === "none" ? "none" : String(style.stroke).startsWith("url(") ? averageColor(style.stroke, true) : paint(style.stroke);
3332
+ const blur = Math.min(64, Math.round(style.blur * scale * Math.sqrt(determinant(matrix)) * 10) / 10);
3333
+ const add = (list) => commands.push(...list.map((item) => ({
3334
+ ...item,
3335
+ ...blur >= .5 ? { blur } : {},
3336
+ ...style.clip ? { clip: style.clip } : {},
3337
+ ...style.blend ? { blend: style.blend } : {}
3338
+ })));
3059
3339
  const common = layer === void 0 ? {} : { layer };
3060
3340
  const strokeWidth = Math.max(1, Math.min(256, (style.strokeWidth || 1) * scale * Math.hypot(matrix[0], matrix[1])));
3061
3341
  const segments = subpath.curves.length;
@@ -3152,21 +3432,131 @@ window.__ModuleLoader__.load({
3152
3432
  }
3153
3433
  return pieces;
3154
3434
  };
3155
- if (fill !== "none" && style.fillOpacity * style.opacity > 0) commands.push(...build(fill, style.fillOpacity * style.opacity, true, ""));
3156
- if (stroke !== "none" && style.strokeOpacity * style.opacity > 0 && style.strokeWidth > 0) commands.push(...build(stroke, style.strokeOpacity * style.opacity, false, "-line"));
3435
+ if (fill !== "none" && style.fillOpacity * style.opacity > 0) {
3436
+ let pieces = build(fill, style.fillOpacity * style.opacity, true, "");
3437
+ if (fillGradient) {
3438
+ const gradient = pieces.length === 1 && [
3439
+ "rectangle",
3440
+ "circle",
3441
+ "polygon",
3442
+ "bezier"
3443
+ ].includes(pieces[0].shape) ? nativeGradient(style.fill, matrix, pieces[0]) : void 0;
3444
+ if (gradient) pieces = [{
3445
+ ...pieces[0],
3446
+ gradient
3447
+ }];
3448
+ else warnings.add("A gradient fill was flattened to its average color (the path was split into several pieces, or its box is empty).");
3449
+ }
3450
+ add(pieces);
3451
+ }
3452
+ if (stroke !== "none" && style.strokeOpacity * style.opacity > 0 && style.strokeWidth > 0) add(build(stroke, style.strokeOpacity * style.opacity, false, "-line"));
3453
+ };
3454
+ const filterBlur = (reference, group) => {
3455
+ const target = byId.get(/^url\(\s*['"]?#([^)'"]+)['"]?\s*\)/.exec(reference)?.[1] ?? "");
3456
+ if (!target || target.name !== "filter") {
3457
+ warnings.add(`Filter ${reference} was ignored (it must be a <filter> defined in the same SVG).`);
3458
+ return 0;
3459
+ }
3460
+ const blurs = target.children.filter((child) => child.name === "feGaussianBlur").map((child) => Math.max(...numbers(child.attrs.stdDeviation ?? "0"), 0));
3461
+ if (target.children.some((child) => child.name !== "feGaussianBlur")) warnings.add(`Filter ${target.attrs.id ?? ""}: only feGaussianBlur is applied; other effects were ignored.`);
3462
+ if (blurs.length && group) warnings.add("A blur filter on a group softens each shape inside it separately.");
3463
+ return Math.max(0, ...blurs);
3464
+ };
3465
+ const clipSubpaths = (child) => {
3466
+ const m = (name) => Number.parseFloat(child.attrs[name] ?? 0);
3467
+ switch (child.name) {
3468
+ case "path": return parsePathData(child.attrs.d);
3469
+ case "rect": {
3470
+ const w = m("width"), h = m("height");
3471
+ if (!(w > 0 && h > 0)) return [];
3472
+ const rx = child.attrs.rx !== void 0 ? m("rx") : child.attrs.ry !== void 0 ? m("ry") : 0, ry = child.attrs.ry !== void 0 ? m("ry") : rx;
3473
+ return [rx > 0 || ry > 0 ? roundedRectPath(m("x"), m("y"), w, h, rx, ry) : polylinePath([
3474
+ [m("x"), m("y")],
3475
+ [m("x") + w, m("y")],
3476
+ [m("x") + w, m("y") + h],
3477
+ [m("x"), m("y") + h]
3478
+ ], true)];
3479
+ }
3480
+ case "circle": return m("r") > 0 ? [ellipsePath(m("cx"), m("cy"), m("r"), m("r"))] : [];
3481
+ case "ellipse": return m("rx") > 0 && m("ry") > 0 ? [ellipsePath(m("cx"), m("cy"), m("rx"), m("ry"))] : [];
3482
+ case "polygon": {
3483
+ const values = numbers(child.attrs.points), pts = [];
3484
+ for (let at = 0; at + 1 < values.length; at += 2) pts.push([values[at], values[at + 1]]);
3485
+ return pts.length >= 3 ? [polylinePath(pts, true)] : [];
3486
+ }
3487
+ default: return [];
3488
+ }
3489
+ };
3490
+ const clipFor = (reference, matrix) => {
3491
+ const target = byId.get(/^url\(\s*['"]?#([^)'"]+)['"]?\s*\)/.exec(reference)?.[1] ?? "");
3492
+ if (!target || target.name !== "clipPath") {
3493
+ warnings.add(`clip-path ${reference} was ignored (it must be a <clipPath> defined in the same SVG).`);
3494
+ return;
3495
+ }
3496
+ const shapes = target.children.filter((child) => [
3497
+ "path",
3498
+ "rect",
3499
+ "circle",
3500
+ "ellipse",
3501
+ "polygon"
3502
+ ].includes(child.name));
3503
+ if (!shapes.length) {
3504
+ warnings.add(`clipPath ${target.attrs.id ?? ""} has no path, rect, circle, ellipse or polygon and was ignored.`);
3505
+ return;
3506
+ }
3507
+ if (shapes.length > 1) warnings.add(`clipPath ${target.attrs.id ?? ""} has several shapes; only the first is used (merge them into one path).`);
3508
+ const placed = multiply(multiply(matrix, parseTransform(target.attrs.transform)), parseTransform(shapes[0].attrs.transform));
3509
+ const subpath = clipSubpaths(shapes[0])[0];
3510
+ if (!subpath) return void 0;
3511
+ const toPoint = ([px, py]) => norm(placed, px, py);
3512
+ const straightPoints = [subpath.start, ...subpath.curves.map((curve) => [curve[4], curve[5]])];
3513
+ if (subpath.straight && straightPoints.length >= 3) {
3514
+ const vertices = subpath.closed ? straightPoints.slice(0, -1) : straightPoints;
3515
+ return vertices.length >= 3 ? {
3516
+ shape: "polygon",
3517
+ points: vertices.slice(0, 2e3).map(toPoint)
3518
+ } : void 0;
3519
+ }
3520
+ if (subpath.curves.length <= MAX_BEZIER_SEGMENTS) return {
3521
+ shape: "bezier",
3522
+ points: [subpath.start, ...subpath.curves.flatMap((curve) => [
3523
+ [curve[0], curve[1]],
3524
+ [curve[2], curve[3]],
3525
+ [curve[4], curve[5]]
3526
+ ])].map(toPoint)
3527
+ };
3528
+ const flat = [subpath.start];
3529
+ let [cx, cy] = subpath.start;
3530
+ for (const [a, b, c1, d, e, g] of subpath.curves) {
3531
+ for (let step = 1; step <= FLATTEN_STEPS; step++) {
3532
+ const t = step / FLATTEN_STEPS, u = 1 - t;
3533
+ flat.push([u * u * u * cx + 3 * u * u * t * a + 3 * u * t * t * c1 + t * t * t * e, u * u * u * cy + 3 * u * u * t * b + 3 * u * t * t * d + t * t * t * g]);
3534
+ }
3535
+ cx = e;
3536
+ cy = g;
3537
+ }
3538
+ return flat.length >= 3 && flat.length <= 2e3 ? {
3539
+ shape: "polygon",
3540
+ points: flat.map(toPoint)
3541
+ } : void 0;
3157
3542
  };
3158
3543
  const walk = (node, matrix, parentStyle, depth) => {
3159
3544
  if (depth > 24) throw Error("SVG is nested too deeply");
3160
3545
  if (UNSUPPORTED.has(node.name)) throw Error(`Unsupported SVG element <${node.name}>. Draw with path, rect, circle, ellipse, line, polyline, polygon, g and use; add text with a native text command.`);
3161
3546
  if (IGNORED.has(node.name)) return;
3162
- for (const name of [
3163
- "clip-path",
3164
- "mask",
3165
- "filter"
3166
- ]) if (node.attrs[name] && node.attrs[name] !== "none") throw Error(`Unsupported SVG attribute ${name}. Bake it into the shapes instead.`);
3547
+ if (node.attrs.mask && node.attrs.mask !== "none") throw Error("Unsupported SVG attribute mask. Bake it into the shapes instead.");
3167
3548
  const style = styleOf(node, parentStyle);
3168
3549
  if (style.display === "none") return;
3550
+ const filterValue = (node.attrs.filter ?? /(?:^|;)\s*filter\s*:\s*([^;]+)/.exec(node.attrs.style ?? "")?.[1] ?? "none").trim();
3551
+ if (filterValue !== "none") style.blur = Math.max(style.blur, filterBlur(filterValue, [
3552
+ "g",
3553
+ "svg",
3554
+ "a",
3555
+ "use"
3556
+ ].includes(node.name)));
3169
3557
  const local = multiply(matrix, parseTransform(node.attrs.transform));
3558
+ const clipValue = (node.attrs["clip-path"] ?? /(?:^|;)\s*clip-path\s*:\s*([^;]+)/.exec(node.attrs.style ?? "")?.[1] ?? "none").trim();
3559
+ if (clipValue !== "none") style.clip = clipFor(clipValue, local);
3170
3560
  const n = (name) => Number.parseFloat(node.attrs[name] ?? 0);
3171
3561
  const finish = (subpaths) => subpaths.forEach((subpath) => emit(subpath, local, style, node.attrs.id));
3172
3562
  switch (node.name) {
@@ -3232,7 +3622,8 @@ window.__ModuleLoader__.load({
3232
3622
  strokeWidth: 1,
3233
3623
  fillOpacity: 1,
3234
3624
  strokeOpacity: 1,
3235
- opacity: 1
3625
+ opacity: 1,
3626
+ blur: 0
3236
3627
  }, 0);
3237
3628
  if (!commands.length) throw Error("The SVG contained no drawable shapes");
3238
3629
  return {
@@ -3270,18 +3661,23 @@ window.__ModuleLoader__.load({
3270
3661
  //#endregion
3271
3662
  //#region src/sketch-commands.js
3272
3663
  const MAX_SKETCH_POINTS = 2e5;
3664
+ const stale = (message) => Object.assign(Error(message), { code: "SKETCH_STALE" });
3273
3665
  const SKETCH_COMMAND_HELP = {
3274
3666
  coordinates: "Assign short meaningful stroke id values for later edits. Text uses two opposite box corners and text content; width is font size in pixels, automatic fitting within the box. Arrow uses two endpoints. Normalized x/y in [0,1]; width is canvas pixels. Read documentId and revision before editing.",
3275
3667
  shapes: "line: exactly two endpoints; rectangle/circle (ellipse alias accepted): exactly two opposite bounding-box corners (circle draws an ellipse within that box); polygon: three or more vertices, closed automatically; pen: ordered path points. bezier: start point, then groups of control1/control2/end; use 4 points for one cubic curve, max 64 segments. Prefer bezier for smooth designed curves instead of many pen samples. fill:true closes and fills the curve. fill:true fills rectangle/circle/polygon. Layers and strokes paint in list order, later ones on top. All commands needed for drawing are described here; no source-code search is required.",
3668
+ guide: "How to draw well here. 1) Plan first: list the parts, the drawing order (back to front) and the rough position and size as fractions of the canvas; keep the plan short. 2) Work big to small and verify after every stage (apply returns progress; look:true or preview shows the result): silhouette and big colour areas, then form and shading, then outlines and small details. 3) Place by measuring, not by eye: with a reference use measure (palette, regions, points, scan) to get exact colours, sizes and edge positions; without one use preview grid and keep proportions (an 8-head figure for realistic bodies, 5–6 heads for anime, a larger head for cute). 4) Depth: every form gets five tones, a highlight, light, half-tone, form shadow and a reflected-light edge; shadows are tinted (blue, purple, teal), never pure black; use 4–8 stop gradients with hue shifts, blur for glow, haze and soft shadows. 5) Build limbs and hair as long tapered shapes (a few overlapping bezier or path shapes), cover joints with rounded shapes, draw the face last on top of the head: eyes (iris, pupil, highlight, lashes), brows, nose and mouth with the right size and spacing, check them with preview box zoomed in. 6) Group related shapes on one layer (hair, face, clothes, background) so they can be adjusted or hidden. 7) Undo a stage that made things worse instead of painting over it. 8) Repeated details (strands, pleats, stars) can be generated by a short script and sent as one svg command. 9) Refine region by region (see below). 10) Stop when the error of every region stops falling or the zoomed previews look right; do not add detail that the picture does not have. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft.",
3276
3669
  commands: {
3277
3670
  preset: "triangle/diamond/star: {op:\"stroke\",id:\"badge\",shape:\"star\",points:[{x:0.1,y:0.1},{x:0.3,y:0.3}],color:\"#ffcc00\",fill:true}. Two opposite box corners; stored as editable polygon. Inspect objectId for one object without repeating full help.",
3278
- stroke: "{op:\"stroke\",layer:1,shape:\"pen|line|arrow|text|rectangle|circle|polygon|bezier\",color:\"#rrggbb\",width:2,opacity:1,fill:false,points:[{x:0.1,y:0.1},...]}",
3671
+ stroke: "{op:\"stroke\",layer:1,shape:\"pen|line|arrow|text|rectangle|circle|polygon|bezier\",color:\"#rrggbb\",width:2,opacity:1,fill:false,points:[{x:0.1,y:0.1},...]}. Optional on any stroke: blend:\"multiply|screen|overlay|soft-light|hard-light|color-dodge|color-burn|darken|lighten|lighter\" (shadows multiply, glows screen or lighter; blends with what is already painted on the same layer; a whole layer can blend with the layers under it: {op:\"layer\",action:\"blend\",id:2,value:\"multiply\"}, value normal to clear) and clip:{shape:\"polygon|bezier|rectangle|circle\",points:[...]} keeps the stroke inside that shape, so shading and highlights stay inside the form they shade (clip.shape none removes it). Optional on filled shapes: gradient:{type:\"linear\",x1:0,y1:0,x2:0,y2:1,stops:[{offset:0,color:\"#ffcc66\"},{offset:1,color:\"#ff6644\",opacity:0.8}]} or {type:\"radial\",cx:0.5,cy:0.5,r:0.5,stops:[...]} (coordinates relative to the shape's own box, so moving or scaling the object keeps it); blur:12 softens any stroke by that many canvas pixels (glow, shadow, haze). Patch gradient:{type:\"none\"} or blur:0 to remove.",
3279
3672
  layer: "Add: {op:\"layer\",action:\"add\",value:\"name\"}; optional id is the NEW unique integer ID, otherwise allocated automatically. after is the existing insertion anchor, defaults to active layer. Other actions: {op:\"layer\",action:\"select|rename|visible|duplicate|up|down|delete|clear\",id:1,value:\"name\"}; id targets an existing layer.",
3280
3673
  curve: "Prefer {op:\"stroke\",shape:\"bezier\",start:{x:0,y:0},segments:[{control1:{x:0.2,y:0},control2:{x:0.8,y:1},end:{x:1,y:1}}],color:\"#123456\"}. Each segment has exactly two controls and an endpoint; no point counting required. Legacy points arrays still accepted. Do not provide both forms.",
3281
3674
  object: "{op:\"object\",layer:1,id:\"title\",action:\"update|duplicate|delete\",patch:{color:\"#0088ff\",text:\"Title\"},transform:{dx:0.05,dy:0,scaleX:1,scaleY:1}}. All patch and transform fields optional. Inspect returns object IDs and bounds. Prefer targeted edits over redrawing layers.",
3282
3675
  resize: "{op:\"resize\",ratio:\"1:1|4:3|3:4|16:9|9:16\"}",
3283
- svg: "{op:\"svg\",svg:\"<svg viewBox=\\\"0 0 1024 768\\\">...</svg>\",layer:1}. Fastest way to draw: send a whole scene as SVG (path with M L H V C S Q T A Z, rect, circle, ellipse, line, polyline, polygon, g, use, transform, fill/stroke/opacity, style=\"...\"); it becomes native editable strokes. The viewBox must match the canvas size (use the width and height from inspect; 4:3 is 1024x768). Gradients are flattened to their average color, so build glows and skies from stacked bands; text, image, filter, clipPath, mask, pattern and CSS classes are refused. Coordinates outside the canvas are clamped. One svg command may hold up to 200000 characters."
3676
+ svg: "{op:\"svg\",svg:\"<svg viewBox=\\\"0 0 1024 768\\\">...</svg>\",layer:1}. Fastest way to draw: send a whole scene as SVG (path with M L H V C S Q T A Z, rect, circle, ellipse, line, polyline, polygon, g, use, transform, fill/stroke/opacity, style=\"...\"); it becomes native editable strokes. The viewBox must match the canvas size (use the width and height from inspect; 4:3 is 1024x768). mix-blend-mode on an element becomes blend, and clip-path=\"url(#id)\" with a clipPath holding one path, rect, circle, ellipse or polygon becomes clip (use the same clipPath for all the shading of a form). Linear and radial gradients on filled shapes are kept as real gradients (fill=\"url(#id)\", objectBoundingBox or userSpaceOnUse, gradientTransform, stop-opacity); a gradient on a stroke line is flattened to its average color. A filter with feGaussianBlur becomes a soft edge on each shape it covers (glows, shadows, haze, depth of field); other filter effects are ignored with a warning. Text, image, mask, pattern and CSS classes are refused. Coordinates outside the canvas are clamped. One svg command may hold up to 200000 characters."
3284
3677
  },
3678
+ measure: "Action measure (not a command): {action:\"measure\",runId,documentId,columns:6,rows:8,box:{x:0,y:0,width:1,height:1},points:[{x:0.5,y:0.3}],palette:8,regions:8,scan:{x1:0,y1:0.5,x2:1,y2:0.5}} compares the drawing with the reference picture and returns error (0 = identical, percent of the colour range), the worst cells (box in 0..1, error, reference and drawing colour as #rrggbb, tone = how much lighter (+) or darker (-) the drawing is than the reference, 0..255; cells:true returns every cell instead of the worst ten, a full colour-error map you can work through), for points the reference and drawing colour there, with palette the main colours of the reference (share of the area), with regions where each main colour sits (share, centre, box that holds most of it), and with scan a ruler laid along a line: the colour runs of the reference and of your drawing along it, with their start and end positions, so you can place edges exactly (scan a row across the hair, a column through the body). box limits it to one part. Every apply also returns progress (error now, error before, three worst cells), so you can see whether a stage helped. Fix the worst cell first, read exact colours from the reference instead of guessing.",
3679
+ undo: "Action undo: {action:\"undo\",runId,documentId,revision (optional),steps:1} takes back the last batches you applied (one per apply) and returns the new revision. Use it when a stage made things worse instead of painting over it.",
3680
+ preview: "Action preview: {action:\"preview\",mode:\"side|diff\",compare:true,grid:true,box:{x:0.3,y:0.1,width:0.4,height:0.3}}. mode side puts the reference and your drawing next to each other; mode diff adds a difference heat map (dark = matches, blue to red = increasingly different in brightness, colour or edges); compare blends both 50/50; grid labels canvas pixels; box zooms into one part (normalised x,y,width,height) so you can check eyes, hands, edges. Apply with look:true returns the side-by-side picture with the result.",
3285
3681
  limits: {
3286
3682
  strokes: MAX_SKETCH_STROKES,
3287
3683
  pointsPerStroke: MAX_STROKE_POINTS,
@@ -3312,13 +3708,14 @@ window.__ModuleLoader__.load({
3312
3708
  "up",
3313
3709
  "down",
3314
3710
  "delete",
3315
- "clear"
3711
+ "clear",
3712
+ "blend"
3316
3713
  ].includes(command.action)) throw Error("Unknown layer action");
3317
3714
  if (command.action === "add") {
3318
3715
  const id = command.id ?? doc.nextId, after = command.after ?? doc.active;
3319
3716
  if (!Number.isSafeInteger(id) || id < 1 || id === Number.MAX_SAFE_INTEGER || doc.layers.some((l) => l.id === id)) throw Error("New layer id must be a unique positive integer; omit id to allocate automatically");
3320
3717
  const next = changeSketchLayer(doc, "add", after);
3321
- if (next === doc) throw Error("Cannot add layer: check the existing after layer and the 8-layer limit");
3718
+ if (next === doc) throw Error(doc.layers.length >= 8 ? "Cannot add layer: the board already has 8 layers, the most it holds. Draw on an existing layer, or delete or merge one first." : "Cannot add layer: after must be the id of an existing layer");
3322
3719
  doc = {
3323
3720
  ...next,
3324
3721
  active: id,
@@ -3354,7 +3751,11 @@ window.__ModuleLoader__.load({
3354
3751
  "opacity",
3355
3752
  "fill",
3356
3753
  "text",
3357
- "points"
3754
+ "points",
3755
+ "gradient",
3756
+ "blur",
3757
+ "blend",
3758
+ "clip"
3358
3759
  ].includes(k))) throw Error("Unsupported object property");
3359
3760
  const changed = command.transform ? transformObject({
3360
3761
  ...original,
@@ -3379,6 +3780,7 @@ window.__ModuleLoader__.load({
3379
3780
  ...original.pressure !== void 0 ? { pressure: original.pressure } : {},
3380
3781
  ...original.brushVersion === 2 ? { brushVersion: 2 } : {}
3381
3782
  };
3783
+ if (patch.gradient === void 0 && original.gradient && !strokes[index].gradient && original.fill) strokes[index].gradient = original.gradient;
3382
3784
  } else throw Error("Unknown object action");
3383
3785
  doc = {
3384
3786
  ...doc,
@@ -3431,6 +3833,8 @@ window.__ModuleLoader__.load({
3431
3833
  if (shape === "text" && (typeof command.text !== "string" || !command.text.trim() || command.text.length > 500 || points[0].x === points[1].x || points[0].y === points[1].y)) throw Error("Text requires 1–500 characters and a non-empty bounding box");
3432
3834
  const id = command.id ?? crypto.randomUUID();
3433
3835
  if (typeof id !== "string" || !id.length || id.length > 100 || layer.strokes.some((s) => s.id === id)) throw Error("Invalid or duplicate object id");
3836
+ const gradient = normalizeGradient(command.gradient), blur = normalizeBlur(command.blur), blend = normalizeBlend(command.blend), clip = normalizeClip(command.clip);
3837
+ if (gradient && !gradientFits(shape, fill)) throw Error("A gradient needs fill:true on a rectangle, circle, polygon or bezier shape");
3434
3838
  const stroke = {
3435
3839
  id,
3436
3840
  ...shape === "text" ? { text: command.text } : {},
@@ -3439,6 +3843,10 @@ window.__ModuleLoader__.load({
3439
3843
  width,
3440
3844
  opacity,
3441
3845
  fill,
3846
+ ...gradient ? { gradient } : {},
3847
+ ...blur ? { blur } : {},
3848
+ ...blend ? { blend } : {},
3849
+ ...clip ? { clip } : {},
3442
3850
  brush: "pen",
3443
3851
  points: points.map((p) => ({
3444
3852
  x: p.x,
@@ -3481,17 +3889,92 @@ window.__ModuleLoader__.load({
3481
3889
  }
3482
3890
  if (request.documentId !== current.documentId) throw Error("Document changed; inspect again");
3483
3891
  if (pending || adapter.busy()) throw Error("Sketch is being edited; retry after it settles");
3892
+ const boxOf = (value) => {
3893
+ if (value === void 0) return void 0;
3894
+ if (!value || typeof value !== "object" || ![
3895
+ "x",
3896
+ "y",
3897
+ "width",
3898
+ "height"
3899
+ ].every((key) => typeof value[key] === "number" && Number.isFinite(value[key])) || value.x < 0 || value.y < 0 || value.width < .02 || value.height < .02 || value.x + value.width > 1.0001 || value.y + value.height > 1.0001) throw Error("box must be {x,y,width,height} inside 0..1, at least 0.02 wide and high");
3900
+ return {
3901
+ x: value.x,
3902
+ y: value.y,
3903
+ width: value.width,
3904
+ height: value.height
3905
+ };
3906
+ };
3484
3907
  if (request.action === "preview") {
3485
3908
  for (const key of ["compare", "grid"]) if (request[key] !== void 0 && typeof request[key] !== "boolean") throw Error(`${key} must be true or false`);
3909
+ if (request.mode !== void 0 && !["side", "diff"].includes(request.mode)) throw Error("mode must be side or diff");
3486
3910
  return {
3487
3911
  ...current,
3488
3912
  png: await adapter.preview({
3489
3913
  compare: request.compare === true,
3490
- grid: request.grid === true
3914
+ grid: request.grid === true,
3915
+ ...request.mode ? { mode: request.mode } : {},
3916
+ ...request.box ? { box: boxOf(request.box) } : {}
3491
3917
  }),
3492
3918
  ...request.grid ? { gridStep: 100 } : {}
3493
3919
  };
3494
3920
  }
3921
+ if (request.action === "measure") {
3922
+ const grid = (name, fallback) => {
3923
+ const value = request[name] ?? fallback;
3924
+ if (!Number.isInteger(value) || value < 1 || value > 16) throw Error(`${name} must be an integer from 1 to 16`);
3925
+ return value;
3926
+ };
3927
+ const points = request.points ?? [];
3928
+ if (!Array.isArray(points) || points.length > 40 || points.some((point) => !point || !finite(point.x, 0, 1) || !finite(point.y, 0, 1))) throw Error("points must be at most 40 {x,y} pairs inside 0..1");
3929
+ if (typeof adapter.measure !== "function") throw Error("measure is not available");
3930
+ const palette = request.palette ?? 0;
3931
+ if (!Number.isInteger(palette) || palette < 0 || palette > 12) throw Error("palette must be an integer from 0 to 12");
3932
+ const regions = request.regions ?? 0;
3933
+ if (!Number.isInteger(regions) || regions < 0 || regions > 12) throw Error("regions must be an integer from 0 to 12");
3934
+ const scan = request.scan;
3935
+ if (scan !== void 0 && (!scan || ![
3936
+ "x1",
3937
+ "y1",
3938
+ "x2",
3939
+ "y2"
3940
+ ].every((key) => finite(scan[key], 0, 1)))) throw Error("scan must be {x1,y1,x2,y2} inside 0..1");
3941
+ const box = boxOf(request.box);
3942
+ try {
3943
+ return {
3944
+ ...current,
3945
+ measure: await adapter.measure({
3946
+ columns: grid("columns", 6),
3947
+ rows: grid("rows", 8),
3948
+ cells: request.cells === true,
3949
+ points,
3950
+ palette,
3951
+ regions,
3952
+ ...scan ? { scan: {
3953
+ x1: scan.x1,
3954
+ y1: scan.y1,
3955
+ x2: scan.x2,
3956
+ y2: scan.y2
3957
+ } } : {},
3958
+ box
3959
+ })
3960
+ };
3961
+ } catch (cause) {
3962
+ const error = new Error(`${cause.message} Correct the request and retry with the same runId.`, { cause });
3963
+ error.code = "SKETCH_INVALID_BATCH";
3964
+ throw error;
3965
+ }
3966
+ }
3967
+ if (request.action === "undo") {
3968
+ const steps = request.steps ?? 1;
3969
+ if (!Number.isInteger(steps) || steps < 1 || steps > 20) throw Error("steps must be an integer from 1 to 20");
3970
+ if (request.revision !== void 0 && request.revision !== current.revision) throw stale("Sketch changed or is being edited; inspect again");
3971
+ if (typeof adapter.undo !== "function") throw Error("undo is not available");
3972
+ const taken = adapter.undo(steps);
3973
+ return {
3974
+ ...adapter.snapshot(),
3975
+ undone: taken
3976
+ };
3977
+ }
3495
3978
  if (![
3496
3979
  "apply",
3497
3980
  "save",
@@ -3507,11 +3990,24 @@ window.__ModuleLoader__.load({
3507
3990
  if (cached.fingerprint !== fingerprint) throw Error("requestId reused with different content");
3508
3991
  return cached.result;
3509
3992
  }
3510
- if (request.revision !== current.revision || adapter.busy()) throw Error("Sketch changed or is being edited; inspect again");
3511
- let changedObjects;
3993
+ if (request.revision === void 0) throw stale("revision is required: copy it from the last result");
3994
+ if (request.revision !== current.revision || adapter.busy()) throw stale("Sketch changed or is being edited; inspect again");
3995
+ let changedObjects, progress, previousError;
3512
3996
  const report = {};
3997
+ const measureNow = async () => {
3998
+ try {
3999
+ return typeof adapter.measure === "function" ? await adapter.measure({
4000
+ columns: 6,
4001
+ rows: 8,
4002
+ points: []
4003
+ }) : void 0;
4004
+ } catch {
4005
+ return;
4006
+ }
4007
+ };
3513
4008
  if (request.action === "apply") {
3514
4009
  const before = adapter.document();
4010
+ previousError = before.layers.some((layer) => layer.image) ? (await measureNow())?.error : void 0;
3515
4011
  let next;
3516
4012
  try {
3517
4013
  next = applySketchCommands(before, request.commands, report);
@@ -3526,6 +4022,14 @@ window.__ModuleLoader__.load({
3526
4022
  layer: l.id,
3527
4023
  id: s.id
3528
4024
  })));
4025
+ if (previousError !== void 0) {
4026
+ const after = await measureNow();
4027
+ if (after) progress = {
4028
+ error: after.error,
4029
+ previous: previousError,
4030
+ worst: after.worst.slice(0, 3)
4031
+ };
4032
+ }
3529
4033
  } else if (request.action === "reference") {
3530
4034
  if (typeof request.image !== "string" || !/^data:image\/(png|jpeg|webp);base64,/.test(request.image) || request.image.length > 19e5) throw Error("A PNG, JPEG or WebP reference image is required");
3531
4035
  pending = true;
@@ -3543,6 +4047,13 @@ window.__ModuleLoader__.load({
3543
4047
  pending = false;
3544
4048
  }
3545
4049
  }
4050
+ if (request.action === "save") {
4051
+ const last = adapter.document?.().layers.some((layer) => layer.image) ? await measureNow() : void 0;
4052
+ if (last) progress = {
4053
+ error: last.error,
4054
+ worst: last.worst.slice(0, 3)
4055
+ };
4056
+ }
3546
4057
  const result = {
3547
4058
  ...adapter.snapshot(),
3548
4059
  ...changedObjects ? {
@@ -3550,7 +4061,8 @@ window.__ModuleLoader__.load({
3550
4061
  changedObjectCount: changedObjects.length
3551
4062
  } : {},
3552
4063
  ...report?.warnings?.length ? { warnings: report.warnings } : {},
3553
- ...report?.clampedPoints ? { clampedPoints: report.clampedPoints } : {}
4064
+ ...report?.clampedPoints ? { clampedPoints: report.clampedPoints } : {},
4065
+ ...progress ? { progress } : {}
3554
4066
  };
3555
4067
  completed.set(key, {
3556
4068
  fingerprint,
@@ -3567,6 +4079,17 @@ window.__ModuleLoader__.load({
3567
4079
  cachedCharacters -= completed.get(oldest).fingerprint.length;
3568
4080
  completed.delete(oldest);
3569
4081
  }
4082
+ if (request.action === "apply" && request.look === true && typeof adapter.preview === "function") {
4083
+ const png = await adapter.preview({
4084
+ compare: false,
4085
+ grid: false,
4086
+ mode: adapter.document().layers.some((layer) => layer.image) ? "side" : void 0
4087
+ });
4088
+ return {
4089
+ ...result,
4090
+ png
4091
+ };
4092
+ }
3570
4093
  return result;
3571
4094
  };
3572
4095
  }
@@ -3627,6 +4150,8 @@ window.__ModuleLoader__.load({
3627
4150
  const target = doc.layers.at(-1);
3628
4151
  target.name = String(layer.name ?? "").slice(0, 40);
3629
4152
  target.visible = layer.visible !== false;
4153
+ const blend = normalizeBlend(layer.blend);
4154
+ if (blend) target.blend = blend;
3630
4155
  if (layer.image) {
3631
4156
  const image = layer.image;
3632
4157
  if (typeof image.src !== "string" || !/^data:image\/png;base64,/.test(image.src) || image.src.length > 8 * 1024 * 1024 || [
@@ -3703,6 +4228,7 @@ window.__ModuleLoader__.load({
3703
4228
  cache.current.clear();
3704
4229
  undo.current = [];
3705
4230
  redo.current = [];
4231
+ if (state.timeline) state.timeline.current = [];
3706
4232
  saved.current = identity;
3707
4233
  dirty.current = false;
3708
4234
  schedule();
@@ -3949,6 +4475,7 @@ window.__ModuleLoader__.load({
3949
4475
  entry.image = layer.image;
3950
4476
  entry.strokes = layer.strokes;
3951
4477
  }
4478
+ context.globalCompositeOperation = layer.blend ?? "source-over";
3952
4479
  if (moving) {
3953
4480
  const ctx = entry.surface.getContext("2d");
3954
4481
  ctx.clearRect(0, 0, size, height);
@@ -3956,65 +4483,240 @@ window.__ModuleLoader__.load({
3956
4483
  paintSketch(ctx, layer.strokes, size, true, height, layer.strokes.length - 1);
3957
4484
  context.drawImage(entry.surface, 0, 0);
3958
4485
  } else context.drawImage(entry.base, 0, 0);
4486
+ context.globalCompositeOperation = "source-over";
3959
4487
  }
3960
4488
  }
3961
4489
  //#endregion
4490
+ //#region src/sketch-diff.js
4491
+ const luma = (data, at) => data[at] * .299 + data[at + 1] * .587 + data[at + 2] * .114;
4492
+ function lumaPlane(picture) {
4493
+ const { data, width, height } = picture, plane = new Float32Array(width * height);
4494
+ for (let i = 0; i < plane.length; i++) plane[i] = luma(data, i * 4);
4495
+ return plane;
4496
+ }
4497
+ function gradient(plane, width, height) {
4498
+ const out = new Float32Array(width * height);
4499
+ for (let y = 1; y < height - 1; y++) for (let x = 1; x < width - 1; x++) {
4500
+ const at = y * width + x;
4501
+ const gx = plane[at - width + 1] + 2 * plane[at + 1] + plane[at + width + 1] - plane[at - width - 1] - 2 * plane[at - 1] - plane[at + width - 1];
4502
+ const gy = plane[at + width - 1] + 2 * plane[at + width] + plane[at + width + 1] - plane[at - width - 1] - 2 * plane[at - width] - plane[at - width + 1];
4503
+ out[at] = Math.hypot(gx, gy) / 4;
4504
+ }
4505
+ return out;
4506
+ }
4507
+ const percentile = (values, share) => {
4508
+ const sample = [];
4509
+ const stride = Math.max(1, Math.floor(values.length / 2e4));
4510
+ for (let i = 0; i < values.length; i += stride) sample.push(values[i]);
4511
+ sample.sort((a, b) => a - b);
4512
+ return sample[Math.min(sample.length - 1, Math.floor(sample.length * share))] || 1e-6;
4513
+ };
4514
+ const STOPS = [
4515
+ [0, [
4516
+ 24,
4517
+ 24,
4518
+ 28
4519
+ ]],
4520
+ [.12, [
4521
+ 24,
4522
+ 24,
4523
+ 28
4524
+ ]],
4525
+ [.3, [
4526
+ 40,
4527
+ 80,
4528
+ 230
4529
+ ]],
4530
+ [.5, [
4531
+ 30,
4532
+ 200,
4533
+ 220
4534
+ ]],
4535
+ [.72, [
4536
+ 250,
4537
+ 220,
4538
+ 40
4539
+ ]],
4540
+ [1, [
4541
+ 235,
4542
+ 30,
4543
+ 30
4544
+ ]]
4545
+ ];
4546
+ const heat = (value) => {
4547
+ for (let i = 1; i < STOPS.length; i++) if (value <= STOPS[i][0]) {
4548
+ const [a, ca] = STOPS[i - 1], [b, cb] = STOPS[i], part = (value - a) / (b - a || 1);
4549
+ return ca.map((channel, k) => channel + (cb[k] - channel) * part);
4550
+ }
4551
+ return STOPS.at(-1)[1];
4552
+ };
4553
+ function diffHeatmap(reference, drawing) {
4554
+ const { width, height } = reference, count = width * height;
4555
+ const lumaR = lumaPlane(reference), lumaD = lumaPlane(drawing);
4556
+ const gradR = gradient(lumaR, width, height), gradD = gradient(lumaD, width, height);
4557
+ const bright = new Float32Array(count), color = new Float32Array(count), edge = new Float32Array(count);
4558
+ for (let i = 0; i < count; i++) {
4559
+ const at = i * 4;
4560
+ const cbR = reference.data[at + 2] - lumaR[i], crR = reference.data[at] - lumaR[i], cbD = drawing.data[at + 2] - lumaD[i], crD = drawing.data[at] - lumaD[i];
4561
+ bright[i] = Math.abs(lumaR[i] - lumaD[i]);
4562
+ color[i] = Math.hypot(cbR - cbD, crR - crD);
4563
+ edge[i] = Math.abs(gradR[i] - gradD[i]);
4564
+ }
4565
+ const [pb, pc, pe] = [
4566
+ bright,
4567
+ color,
4568
+ edge
4569
+ ].map((values) => percentile(values, .97));
4570
+ const out = new Uint8ClampedArray(count * 4);
4571
+ for (let i = 0; i < count; i++) {
4572
+ const mix = .3 * bright[i] / pb + .45 * color[i] / pc + .25 * edge[i] / pe;
4573
+ const [r, g, b] = heat(Math.min(1, Math.pow(Math.min(1, mix / 1.3), .7)));
4574
+ out[i * 4] = r;
4575
+ out[i * 4 + 1] = g;
4576
+ out[i * 4 + 2] = b;
4577
+ out[i * 4 + 3] = 255;
4578
+ }
4579
+ return {
4580
+ data: out,
4581
+ width,
4582
+ height
4583
+ };
4584
+ }
4585
+ //#endregion
3962
4586
  //#region src/sketch-preview.js
3963
4587
  const GRID_STEP = 100;
3964
- function composeSketchPreview({ doc, images, width, height, options = {}, makeSurface, paintLayers }) {
3965
- const surface = makeSurface(width, height), context = surface.getContext("2d");
4588
+ const PANE_WIDTH = 560;
4589
+ const PANE_HEIGHT = 760;
4590
+ const LABEL = 22;
4591
+ const GAP = 10;
4592
+ const MAX_SURFACE = 4096;
4593
+ const referenceOf = (doc) => ({
4594
+ ...doc,
4595
+ layers: doc.layers.map((layer) => ({
4596
+ ...layer,
4597
+ strokes: [],
4598
+ visible: Boolean(layer.image)
4599
+ }))
4600
+ });
4601
+ const drawingOf = (doc) => ({
4602
+ ...doc,
4603
+ layers: doc.layers.map((layer) => ({
4604
+ ...layer,
4605
+ image: void 0
4606
+ }))
4607
+ });
4608
+ function composeSketchPreview({ doc, images, width, height, options = {}, makeSurface, paintLayers, readPixels = (surface) => surface.getContext("2d").getImageData(0, 0, surface.width, surface.height) }) {
4609
+ const hasReference = doc.layers.some((layer) => layer.image);
4610
+ const mode = options.mode === "side" || options.mode === "diff" ? options.mode : void 0;
4611
+ if ((options.compare || mode) && !hasReference) throw Error("compare needs a reference picture layer on the board; ask the user to add the reference with the pictures button");
4612
+ const box = options.box;
4613
+ const region = box ? {
4614
+ x: box.x * width,
4615
+ y: box.y * height,
4616
+ w: box.width * width,
4617
+ h: box.height * height
4618
+ } : {
4619
+ x: 0,
4620
+ y: 0,
4621
+ w: width,
4622
+ h: height
4623
+ };
4624
+ const zoom = box ? Math.max(1, Math.min(3, 900 / Math.max(region.w, region.h), MAX_SURFACE / width, MAX_SURFACE / height)) : 1;
4625
+ const render = (variant) => {
4626
+ const bigWidth = Math.round(width * zoom), bigHeight = Math.round(height * zoom);
4627
+ const big = makeSurface(bigWidth, bigHeight);
4628
+ paintLayers(big.getContext("2d"), variant, /* @__PURE__ */ new Map(), bigWidth, bigHeight, void 0, images);
4629
+ if (!box) return big;
4630
+ const out = makeSurface(Math.max(1, Math.round(region.w * zoom)), Math.max(1, Math.round(region.h * zoom)));
4631
+ out.getContext("2d").drawImage(big, Math.round(region.x * zoom), Math.round(region.y * zoom), out.width, out.height, 0, 0, out.width, out.height);
4632
+ return out;
4633
+ };
4634
+ const grid = (context, w, h) => {
4635
+ if (options.grid) paintGrid(context, w, h, region, zoom);
4636
+ };
4637
+ if (mode) {
4638
+ const reference = render(referenceOf(doc)), drawing = render(drawingOf(doc));
4639
+ const scale = Math.min(1, PANE_WIDTH / reference.width, PANE_HEIGHT / reference.height);
4640
+ const paneWidth = Math.max(1, Math.round(reference.width * scale)), paneHeight = Math.max(1, Math.round(reference.height * scale));
4641
+ const panes = mode === "diff" ? 3 : 2;
4642
+ const surface = makeSurface(panes * paneWidth + (panes - 1) * GAP, paneHeight + LABEL), context = surface.getContext("2d");
4643
+ context.fillStyle = "#ffffff";
4644
+ context.fillRect(0, 0, surface.width, surface.height);
4645
+ const labels = [
4646
+ "reference",
4647
+ "drawing",
4648
+ "difference"
4649
+ ];
4650
+ const place = (source, index) => {
4651
+ context.drawImage(source, index * (paneWidth + GAP), LABEL, paneWidth, paneHeight);
4652
+ context.save();
4653
+ context.beginPath();
4654
+ context.rect(index * (paneWidth + GAP), LABEL, paneWidth, paneHeight);
4655
+ context.clip();
4656
+ context.translate(index * (paneWidth + GAP), LABEL);
4657
+ context.scale(scale, scale);
4658
+ grid(context, reference.width, reference.height);
4659
+ context.restore();
4660
+ context.fillStyle = "#222222";
4661
+ context.font = "14px sans-serif";
4662
+ context.textBaseline = "top";
4663
+ context.fillText(labels[index], index * (paneWidth + GAP) + 4, 3);
4664
+ };
4665
+ place(reference, 0);
4666
+ place(drawing, 1);
4667
+ if (mode === "diff") {
4668
+ const heat = makeSurface(reference.width, reference.height);
4669
+ const pixels = diffHeatmap(readPixels(reference), readPixels(drawing));
4670
+ heat.getContext("2d").putImageData(new ImageData(pixels.data, pixels.width, pixels.height), 0, 0);
4671
+ place(heat, 2);
4672
+ }
4673
+ return surface.toDataURL("image/png");
4674
+ }
3966
4675
  if (options.compare) {
3967
- if (!doc.layers.some((layer) => layer.image)) throw Error("compare needs a reference picture layer on the board; ask the user to add the reference with the pictures button");
3968
- const reference = makeSurface(width, height), drawing = makeSurface(width, height);
3969
- paintLayers(reference.getContext("2d"), {
3970
- ...doc,
3971
- layers: doc.layers.map((layer) => ({
3972
- ...layer,
3973
- strokes: [],
3974
- visible: Boolean(layer.image)
3975
- }))
3976
- }, /* @__PURE__ */ new Map(), width, height, void 0, images);
3977
- paintLayers(drawing.getContext("2d"), {
3978
- ...doc,
3979
- layers: doc.layers.map((layer) => ({
3980
- ...layer,
3981
- image: void 0
3982
- }))
3983
- }, /* @__PURE__ */ new Map(), width, height, void 0, images);
4676
+ const reference = render(referenceOf(doc)), drawing = render(drawingOf(doc));
4677
+ const surface = makeSurface(reference.width, reference.height), context = surface.getContext("2d");
3984
4678
  context.drawImage(reference, 0, 0);
3985
4679
  context.globalAlpha = .5;
3986
4680
  context.drawImage(drawing, 0, 0);
3987
4681
  context.globalAlpha = 1;
3988
- } else paintLayers(context, doc, /* @__PURE__ */ new Map(), width, height, void 0, images);
3989
- if (options.grid) paintGrid(context, width, height);
4682
+ grid(context, surface.width, surface.height);
4683
+ return surface.toDataURL("image/png");
4684
+ }
4685
+ const surface = render(doc);
4686
+ grid(surface.getContext("2d"), surface.width, surface.height);
3990
4687
  return surface.toDataURL("image/png");
3991
4688
  }
3992
- function paintGrid(context, width, height) {
4689
+ function paintGrid(context, width, height, region, zoom) {
4690
+ const step = zoom > 1.6 ? GRID_STEP / 2 : GRID_STEP;
3993
4691
  context.save();
3994
4692
  context.lineWidth = 1;
3995
4693
  context.strokeStyle = "rgba(214,0,120,0.45)";
3996
4694
  context.fillStyle = "rgba(214,0,120,0.9)";
3997
4695
  context.font = "12px sans-serif";
3998
4696
  context.textBaseline = "top";
3999
- for (let x = GRID_STEP; x < width; x += GRID_STEP) {
4697
+ for (let canvasX = Math.ceil(region.x / step) * step; canvasX < region.x + region.w; canvasX += step) {
4698
+ if (canvasX <= 0) continue;
4699
+ const x = Math.round((canvasX - region.x) * zoom);
4000
4700
  context.beginPath();
4001
4701
  context.moveTo(x + .5, 0);
4002
4702
  context.lineTo(x + .5, height);
4003
4703
  context.stroke();
4004
- context.fillText(String(x), x + 3, 2);
4704
+ context.fillText(String(canvasX), x + 3, 2);
4005
4705
  }
4006
- for (let y = GRID_STEP; y < height; y += GRID_STEP) {
4706
+ for (let canvasY = Math.ceil(region.y / step) * step; canvasY < region.y + region.h; canvasY += step) {
4707
+ if (canvasY <= 0) continue;
4708
+ const y = Math.round((canvasY - region.y) * zoom);
4007
4709
  context.beginPath();
4008
4710
  context.moveTo(0, y + .5);
4009
4711
  context.lineTo(width, y + .5);
4010
4712
  context.stroke();
4011
- context.fillText(String(y), 3, y + 2);
4713
+ context.fillText(String(canvasY), 3, y + 2);
4012
4714
  }
4013
4715
  context.restore();
4014
4716
  }
4015
4717
  //#endregion
4016
4718
  //#region src/sketch-files.jsx
4017
- function SketchFiles({ save, load, fresh, importImage, download, hasContent, disabled, t, runOperation }) {
4719
+ function SketchFiles({ save, load, fresh, importImage, download, hasContent, disabled, t, runOperation, extra }) {
4018
4720
  const [open, setOpen] = (0, react.useState)(false), [rows, setRows] = (0, react.useState)([]), [name, setName] = (0, react.useState)(""), [remove, setRemove] = (0, react.useState)(null), [working, setWorking] = (0, react.useState)(false);
4019
4721
  const [format, setFormat] = (0, react.useState)("png");
4020
4722
  const input = (0, react.useRef)(null), host = (0, react.useRef)(null);
@@ -4056,6 +4758,7 @@ window.__ModuleLoader__.load({
4056
4758
  },
4057
4759
  children: t("sketchFiles")
4058
4760
  }),
4761
+ extra,
4059
4762
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
4060
4763
  ref: input,
4061
4764
  type: "file",
@@ -4171,6 +4874,491 @@ window.__ModuleLoader__.load({
4171
4874
  });
4172
4875
  }
4173
4876
  //#endregion
4877
+ //#region src/sketch-replay.js
4878
+ const MAX_REPLAY_STATES = 2e3;
4879
+ function recordReplayState(states, doc) {
4880
+ if (states.at(-1) === doc) return;
4881
+ states.push(doc);
4882
+ if (states.length > 2e3) states.splice(0, states.length - MAX_REPLAY_STATES);
4883
+ }
4884
+ function appendedStrokes(before, after) {
4885
+ for (const layer of before.layers) {
4886
+ const next = after.layers.find((item) => item.id === layer.id);
4887
+ if (!next || next.image !== layer.image || layer.strokes.length > next.strokes.length || layer.strokes.some((stroke, i) => stroke !== next.strokes[i])) return void 0;
4888
+ }
4889
+ const added = [];
4890
+ for (const layer of after.layers) {
4891
+ const old = before.layers.find((item) => item.id === layer.id)?.strokes.length ?? 0;
4892
+ for (let i = old; i < layer.strokes.length; i++) added.push({
4893
+ layer: layer.id,
4894
+ stroke: layer.strokes[i]
4895
+ });
4896
+ }
4897
+ return added;
4898
+ }
4899
+ function replaySteps(states) {
4900
+ const steps = [];
4901
+ for (let index = 1; index < states.length; index++) {
4902
+ const before = states[index - 1], after = states[index];
4903
+ if (before === after) continue;
4904
+ const added = appendedStrokes(before, after);
4905
+ steps.push(added?.length ? {
4906
+ type: "draw",
4907
+ before,
4908
+ after,
4909
+ added
4910
+ } : {
4911
+ type: "jump",
4912
+ before,
4913
+ after,
4914
+ added: []
4915
+ });
4916
+ }
4917
+ return steps;
4918
+ }
4919
+ const lengthOf = (stroke, width, height) => {
4920
+ const points = stroke.points;
4921
+ let total = 0;
4922
+ for (let i = 1; i < points.length; i++) total += Math.hypot((points[i].x - points[i - 1].x) * width, (points[i].y - points[i - 1].y) * height);
4923
+ return total;
4924
+ };
4925
+ const OUTLINE_SHARE = .3;
4926
+ function strokePath(stroke) {
4927
+ const [first, last] = [stroke.points[0], stroke.points.at(-1)];
4928
+ if (!first || stroke.shape === "text" || stroke.shape === "eraser") return void 0;
4929
+ switch (stroke.shape) {
4930
+ case "line":
4931
+ case "arrow": return [first, last];
4932
+ case "bezier": return flattenSketchCurve(stroke, 1024, 1024);
4933
+ case "polygon": return [...stroke.points, first];
4934
+ case "rectangle": return [
4935
+ first,
4936
+ {
4937
+ x: last.x,
4938
+ y: first.y
4939
+ },
4940
+ last,
4941
+ {
4942
+ x: first.x,
4943
+ y: last.y
4944
+ },
4945
+ first
4946
+ ];
4947
+ case "circle": {
4948
+ const cx = (first.x + last.x) / 2, cy = (first.y + last.y) / 2, rx = Math.abs(last.x - first.x) / 2, ry = Math.abs(last.y - first.y) / 2;
4949
+ return Array.from({ length: 49 }, (_, i) => ({
4950
+ x: cx + rx * Math.cos(i / 48 * Math.PI * 2),
4951
+ y: cy + ry * Math.sin(i / 48 * Math.PI * 2)
4952
+ }));
4953
+ }
4954
+ default: return stroke.points;
4955
+ }
4956
+ }
4957
+ function partialStroke(stroke, fraction) {
4958
+ if (fraction >= 1) return stroke;
4959
+ if (!(fraction > 0)) return {
4960
+ ...stroke,
4961
+ opacity: 0
4962
+ };
4963
+ const filled = stroke.fill && stroke.shape !== "pen";
4964
+ if (filled && !stroke.gradient && fraction >= OUTLINE_SHARE && stroke.shape !== "text") {
4965
+ const reveal = (fraction - OUTLINE_SHARE) / (1 - OUTLINE_SHARE);
4966
+ const stops = [
4967
+ {
4968
+ offset: 0,
4969
+ color: stroke.color
4970
+ },
4971
+ {
4972
+ offset: reveal,
4973
+ color: stroke.color
4974
+ },
4975
+ {
4976
+ offset: Math.min(1, reveal + .002),
4977
+ color: stroke.color,
4978
+ opacity: 0
4979
+ },
4980
+ {
4981
+ offset: 1,
4982
+ color: stroke.color,
4983
+ opacity: 0
4984
+ }
4985
+ ];
4986
+ return {
4987
+ ...stroke,
4988
+ gradient: {
4989
+ type: "linear",
4990
+ x1: 0,
4991
+ y1: 0,
4992
+ x2: 0,
4993
+ y2: 1,
4994
+ stops
4995
+ }
4996
+ };
4997
+ }
4998
+ const path = strokePath(stroke);
4999
+ if (!path || path.length < 2) return {
5000
+ ...stroke,
5001
+ opacity: (stroke.opacity ?? 1) * Math.max(0, fraction)
5002
+ };
5003
+ const share = filled ? fraction / OUTLINE_SHARE : fraction;
5004
+ const lengths = path.slice(1).map((point, i) => Math.hypot(point.x - path[i].x, point.y - path[i].y));
5005
+ let remaining = lengths.reduce((sum, value) => sum + value, 0) * Math.max(0, share);
5006
+ const points = [path[0]];
5007
+ for (let i = 0; i < lengths.length; i++) {
5008
+ if (remaining >= lengths[i]) {
5009
+ points.push(path[i + 1]);
5010
+ remaining -= lengths[i];
5011
+ continue;
5012
+ }
5013
+ const part = lengths[i] ? remaining / lengths[i] : 0;
5014
+ points.push({
5015
+ x: path[i].x + (path[i + 1].x - path[i].x) * part,
5016
+ y: path[i].y + (path[i + 1].y - path[i].y) * part
5017
+ });
5018
+ break;
5019
+ }
5020
+ if (points.length < 2) return {
5021
+ ...stroke,
5022
+ opacity: 0
5023
+ };
5024
+ const { gradient, blur, ...rest } = stroke;
5025
+ return filled ? {
5026
+ ...rest,
5027
+ shape: "pen",
5028
+ fill: false,
5029
+ width: Math.max(2, Math.min(3, stroke.width ?? 2)),
5030
+ opacity: .85,
5031
+ points
5032
+ } : {
5033
+ ...rest,
5034
+ shape: "pen",
5035
+ fill: false,
5036
+ points,
5037
+ ...blur ? { blur } : {}
5038
+ };
5039
+ }
5040
+ function strokeWeight(stroke, width = 1024, height = 1024) {
5041
+ if (stroke.fill && stroke.shape !== "pen") return 2.2;
5042
+ return .6 + Math.min(4, Math.sqrt(lengthOf(stroke, width, height)) / 8);
5043
+ }
5044
+ function planReplay(steps, duration, width = 1024, height = 1024) {
5045
+ const items = steps.map((step) => ({
5046
+ step,
5047
+ weight: step.type === "jump" ? 6 : step.added.reduce((sum, item) => sum + strokeWeight(item.stroke, width, height), 0) + 6
5048
+ }));
5049
+ const total = items.reduce((sum, item) => sum + item.weight, 0) || 1;
5050
+ let at = 0;
5051
+ return items.map(({ step, weight }) => {
5052
+ const span = duration * weight / total;
5053
+ const drawing = span - Math.min(span * .12, 500);
5054
+ const drawWeight = step.added.reduce((sum, item) => sum + strokeWeight(item.stroke, width, height), 0) || 1;
5055
+ let cursor = at;
5056
+ const strokes = step.added.map((item) => {
5057
+ const own = drawing * strokeWeight(item.stroke, width, height) / drawWeight;
5058
+ const entry = {
5059
+ ...item,
5060
+ start: cursor,
5061
+ end: cursor + own
5062
+ };
5063
+ cursor += own;
5064
+ return entry;
5065
+ });
5066
+ const planned = {
5067
+ step,
5068
+ start: at,
5069
+ end: at + span,
5070
+ strokes
5071
+ };
5072
+ at += span;
5073
+ return planned;
5074
+ });
5075
+ }
5076
+ function replayFrame(plan, time) {
5077
+ if (!plan.length) return void 0;
5078
+ const last = plan.at(-1);
5079
+ if (time >= last.end) return { doc: last.step.after };
5080
+ const item = plan.find((entry) => time < entry.end) ?? last;
5081
+ if (item.step.type === "jump" || !item.strokes.length) return { doc: time < item.start + (item.end - item.start) / 2 ? item.step.before : item.step.after };
5082
+ const done = item.strokes.filter((entry) => time >= entry.end);
5083
+ const current = item.strokes.find((entry) => time >= entry.start && time < entry.end);
5084
+ const layers = item.step.after.layers.map((layer) => {
5085
+ const base = item.step.before.layers.find((old) => old.id === layer.id)?.strokes ?? [];
5086
+ const extra = [...done.filter((entry) => entry.layer === layer.id).map((entry) => entry.stroke)];
5087
+ if (current?.layer === layer.id) extra.push(partialStroke(current.stroke, (time - current.start) / (current.end - current.start)));
5088
+ return {
5089
+ ...layer,
5090
+ strokes: extra.length ? [...base, ...extra] : base
5091
+ };
5092
+ });
5093
+ return {
5094
+ doc: {
5095
+ ...item.step.after,
5096
+ layers
5097
+ },
5098
+ moving: current?.layer
5099
+ };
5100
+ }
5101
+ //#endregion
5102
+ //#region src/sketch-replay.jsx
5103
+ const SPEEDS = [
5104
+ [
5105
+ "fast",
5106
+ 12e3,
5107
+ "sketchReplayFast"
5108
+ ],
5109
+ [
5110
+ "normal",
5111
+ 3e4,
5112
+ "sketchReplayNormal"
5113
+ ],
5114
+ [
5115
+ "slow",
5116
+ 6e4,
5117
+ "sketchReplaySlow"
5118
+ ]
5119
+ ];
5120
+ const VIDEO_TYPES = [
5121
+ "video/webm;codecs=vp9",
5122
+ "video/webm;codecs=vp8",
5123
+ "video/webm"
5124
+ ];
5125
+ function SketchReplay({ states, current, images, name, onClose, t }) {
5126
+ const canvas = (0, react.useRef)(null);
5127
+ const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
5128
+ const clock = (0, react.useRef)({
5129
+ time: 0,
5130
+ last: 0,
5131
+ playing: true,
5132
+ recorder: null
5133
+ });
5134
+ const [speed, setSpeed] = (0, react.useState)("normal");
5135
+ const [playing, setPlaying] = (0, react.useState)(true);
5136
+ const [recording, setRecording] = (0, react.useState)(false);
5137
+ const [progress, setProgress] = (0, react.useState)(0);
5138
+ const [note, setNote] = (0, react.useState)("");
5139
+ const [video, setVideo] = (0, react.useState)(null);
5140
+ const width = current.width ?? 1024, height = current.height ?? 1024;
5141
+ const duration = SPEEDS.find((item) => item[0] === speed)[1];
5142
+ const steps = (0, react.useMemo)(() => replaySteps([...states, current]), [states, current]);
5143
+ const plan = (0, react.useMemo)(() => planReplay(steps, duration, width, height), [
5144
+ steps,
5145
+ duration,
5146
+ width,
5147
+ height
5148
+ ]);
5149
+ const total = plan.at(-1)?.end ?? 0;
5150
+ const paint = (time) => {
5151
+ const target = canvas.current;
5152
+ if (!target) return;
5153
+ const frame = replayFrame(plan, time);
5154
+ paintSketchLayers(target.getContext("2d"), frame?.doc ?? current, cache.current, width, height, frame?.moving, images);
5155
+ };
5156
+ (0, react.useEffect)(() => {
5157
+ clock.current.time = 0;
5158
+ clock.current.last = 0;
5159
+ cache.current.clear();
5160
+ let frame = 0;
5161
+ const tick = (now) => {
5162
+ const state = clock.current;
5163
+ if (state.playing) {
5164
+ state.time = Math.min(total, state.time + (state.last ? now - state.last : 0));
5165
+ if (state.time >= total) {
5166
+ state.playing = false;
5167
+ setPlaying(false);
5168
+ if (state.recorder) window.setTimeout(() => state.recorder?.stop(), 600);
5169
+ }
5170
+ }
5171
+ state.last = now;
5172
+ paint(state.time);
5173
+ setProgress(total ? state.time / total : 1);
5174
+ frame = requestAnimationFrame(tick);
5175
+ };
5176
+ frame = requestAnimationFrame(tick);
5177
+ return () => cancelAnimationFrame(frame);
5178
+ }, [plan]);
5179
+ (0, react.useEffect)(() => () => {
5180
+ if (video) URL.revokeObjectURL(video.url);
5181
+ }, [video]);
5182
+ (0, react.useEffect)(() => () => {
5183
+ if (clock.current.recorder?.state === "recording") {
5184
+ clock.current.recorder.onstop = null;
5185
+ clock.current.recorder.stop();
5186
+ }
5187
+ }, []);
5188
+ const toggle = () => {
5189
+ const state = clock.current;
5190
+ if (state.time >= total) {
5191
+ state.time = 0;
5192
+ cache.current.clear();
5193
+ }
5194
+ state.playing = !state.playing;
5195
+ setPlaying(state.playing);
5196
+ };
5197
+ const seek = (value) => {
5198
+ clock.current.time = value * total;
5199
+ clock.current.playing = false;
5200
+ setPlaying(false);
5201
+ cache.current.clear();
5202
+ };
5203
+ const record = () => {
5204
+ if (recording) {
5205
+ clock.current.recorder?.stop();
5206
+ return;
5207
+ }
5208
+ const type = VIDEO_TYPES.find((item) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(item));
5209
+ if (!type || !canvas.current?.captureStream) {
5210
+ setNote(t("sketchReplayUnsupported"));
5211
+ return;
5212
+ }
5213
+ setNote("");
5214
+ const chunks = [];
5215
+ const recorder = new MediaRecorder(canvas.current.captureStream(30), {
5216
+ mimeType: type,
5217
+ videoBitsPerSecond: 8e6
5218
+ });
5219
+ recorder.ondataavailable = (event) => {
5220
+ if (event.data.size) chunks.push(event.data);
5221
+ };
5222
+ recorder.onstop = () => {
5223
+ clock.current.recorder = null;
5224
+ setRecording(false);
5225
+ setVideo({
5226
+ url: URL.createObjectURL(new Blob(chunks, { type: "video/webm" })),
5227
+ file: `${(name || "sketch").replace(/[\\/:*?"<>|\u0000-\u001f]/g, "-").slice(0, 80)}-${t("sketchReplayFileSuffix")}.webm`
5228
+ });
5229
+ };
5230
+ clock.current.time = 0;
5231
+ clock.current.playing = true;
5232
+ cache.current.clear();
5233
+ clock.current.recorder = recorder;
5234
+ setPlaying(true);
5235
+ setRecording(true);
5236
+ recorder.start(250);
5237
+ };
5238
+ const stop = () => {
5239
+ if (clock.current.recorder?.state === "recording") {
5240
+ clock.current.recorder.onstop = null;
5241
+ clock.current.recorder.stop();
5242
+ clock.current.recorder = null;
5243
+ setRecording(false);
5244
+ }
5245
+ onClose();
5246
+ };
5247
+ const clock0 = Math.round(progress * total / 1e3), clock1 = Math.round(total / 1e3);
5248
+ const mmss = (seconds) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
5249
+ const icon = (path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
5250
+ viewBox: "0 0 24 24",
5251
+ width: "18",
5252
+ height: "18",
5253
+ "aria-hidden": "true",
5254
+ fill: "currentColor",
5255
+ children: path
5256
+ });
5257
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
5258
+ className: "codexSketchReplay",
5259
+ role: "dialog",
5260
+ "aria-label": t("sketchReplayTitle"),
5261
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: t("sketchReplayTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
5262
+ type: "button",
5263
+ className: "codexSketchReplayClose",
5264
+ onClick: stop,
5265
+ "aria-label": t("sketchReplayClose"),
5266
+ children: [icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M6.4 5 12 10.6 17.6 5 19 6.4 13.4 12 19 17.6 17.6 19 12 13.4 6.4 19 5 17.6 10.6 12 5 6.4z" })), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("sketchReplayClose") })]
5267
+ })] }), video ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
5268
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
5269
+ className: "codexSketchReplayStage",
5270
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("video", {
5271
+ src: video.url,
5272
+ controls: true,
5273
+ autoPlay: true,
5274
+ loop: true
5275
+ })
5276
+ }),
5277
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5278
+ className: "codexSketchReplayBar",
5279
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
5280
+ className: "codexSketchReplaySave",
5281
+ href: video.url,
5282
+ download: video.file,
5283
+ children: t("sketchReplaySave")
5284
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
5285
+ type: "button",
5286
+ onClick: () => setVideo(null),
5287
+ children: t("sketchReplayAgain")
5288
+ })]
5289
+ }),
5290
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchReplaySaveHint") })
5291
+ ] }) : steps.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("sketchReplayEmpty") }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
5292
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
5293
+ className: "codexSketchReplayStage",
5294
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("canvas", {
5295
+ ref: canvas,
5296
+ width,
5297
+ height,
5298
+ style: {
5299
+ aspectRatio: `${width} / ${height}`,
5300
+ width: `min(100cqw, calc(100cqh * ${width / height}))`
5301
+ }
5302
+ })
5303
+ }),
5304
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5305
+ className: "codexSketchReplayBar",
5306
+ children: [
5307
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
5308
+ type: "button",
5309
+ className: "codexSketchReplayPlay",
5310
+ disabled: recording,
5311
+ onClick: toggle,
5312
+ "aria-label": playing ? t("sketchReplayPause") : t("sketchReplayPlay"),
5313
+ children: playing ? icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" })) : icon(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5.2v13.6L19 12z" }))
5314
+ }),
5315
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
5316
+ className: "codexSketchReplayTime",
5317
+ children: [
5318
+ mmss(clock0),
5319
+ " / ",
5320
+ mmss(clock1)
5321
+ ]
5322
+ }),
5323
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
5324
+ type: "range",
5325
+ min: "0",
5326
+ max: "1",
5327
+ step: "0.001",
5328
+ value: progress,
5329
+ disabled: recording,
5330
+ "aria-label": t("sketchReplayTitle"),
5331
+ onChange: (event) => seek(Number(event.target.value))
5332
+ }),
5333
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
5334
+ className: "codexSketchSegment",
5335
+ role: "group",
5336
+ "aria-label": t("sketchReplaySpeed"),
5337
+ children: SPEEDS.map(([value, , label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
5338
+ type: "button",
5339
+ "aria-pressed": speed === value,
5340
+ disabled: recording,
5341
+ onClick: () => setSpeed(value),
5342
+ children: t(label)
5343
+ }, value))
5344
+ }),
5345
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
5346
+ type: "button",
5347
+ className: "codexSketchReplayRecord",
5348
+ "data-recording": recording || void 0,
5349
+ onClick: record,
5350
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", { "aria-hidden": "true" }), recording ? t("sketchReplayStopRecording") : t("sketchReplayRecord")]
5351
+ })
5352
+ ]
5353
+ }),
5354
+ note ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", {
5355
+ role: "alert",
5356
+ children: note
5357
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: t("sketchReplayHint") })
5358
+ ] })]
5359
+ });
5360
+ }
5361
+ //#endregion
4174
5362
  //#region src/sketch-size-control.jsx
4175
5363
  function SketchSizeControl({ value, onChange, onStart, onEnd, label, disabled, min = 2, max = 128, mode, modes, onModeChange, suffix = "" }) {
4176
5364
  const active = (0, react.useRef)(false);
@@ -4228,7 +5416,7 @@ window.__ModuleLoader__.load({
4228
5416
  }
4229
5417
  //#endregion
4230
5418
  //#region src/sketch-agent-run.js
4231
- function createSketchAgentRun({ execute, open, changed, busy = () => false, idleMs = 18e4 }) {
5419
+ function createSketchAgentRun({ execute, open, changed, busy = () => false, idleMs = 9e5 }) {
4232
5420
  let state = "idle", generation = 0, runNumber = 0, pending = false, runId, timer, completed;
4233
5421
  const update = (next) => {
4234
5422
  state = next;
@@ -4302,7 +5490,7 @@ window.__ModuleLoader__.load({
4302
5490
  update("finished");
4303
5491
  return completed.value;
4304
5492
  } catch (error) {
4305
- if (version === generation && error.code === "SKETCH_INVALID_BATCH") throw error;
5493
+ if (version === generation && (error.code === "SKETCH_INVALID_BATCH" || error.code === "SKETCH_STALE")) throw error;
4306
5494
  if (version === generation) {
4307
5495
  update("failed");
4308
5496
  throw new Error(`${error.message} Call inspect to obtain the current runId and revision before retrying.`, { cause: error });
@@ -4415,11 +5603,260 @@ window.__ModuleLoader__.load({
4415
5603
  };
4416
5604
  }
4417
5605
  //#endregion
5606
+ //#region src/sketch-measure.js
5607
+ const hex = (r, g, b) => "#" + [
5608
+ r,
5609
+ g,
5610
+ b
5611
+ ].map((value) => Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0")).join("");
5612
+ function average(picture, x0, y0, x1, y1) {
5613
+ const { data, width, height } = picture;
5614
+ const left = Math.max(0, Math.floor(x0)), top = Math.max(0, Math.floor(y0)), right = Math.min(width, Math.max(left + 1, Math.ceil(x1))), bottom = Math.min(height, Math.max(top + 1, Math.ceil(y1)));
5615
+ let r = 0, g = 0, b = 0, n = 0;
5616
+ for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
5617
+ const at = (y * width + x) * 4;
5618
+ r += data[at];
5619
+ g += data[at + 1];
5620
+ b += data[at + 2];
5621
+ n++;
5622
+ }
5623
+ return n ? [
5624
+ r / n,
5625
+ g / n,
5626
+ b / n
5627
+ ] : [
5628
+ 255,
5629
+ 255,
5630
+ 255
5631
+ ];
5632
+ }
5633
+ function measureDifference(reference, drawing, { columns = 6, rows = 8, worst = 10 } = {}) {
5634
+ const { width, height } = reference;
5635
+ const cells = [];
5636
+ let total = 0;
5637
+ for (let row = 0; row < rows; row++) for (let column = 0; column < columns; column++) {
5638
+ const x0 = column * width / columns, x1 = (column + 1) * width / columns, y0 = row * height / rows, y1 = (row + 1) * height / rows;
5639
+ let sum = 0, n = 0;
5640
+ const step = Math.max(1, Math.floor(Math.min(x1 - x0, y1 - y0) / 24));
5641
+ for (let y = Math.floor(y0); y < y1; y += step) for (let x = Math.floor(x0); x < x1; x += step) {
5642
+ const at = (y * width + x) * 4;
5643
+ sum += Math.abs(reference.data[at] - drawing.data[at]) + Math.abs(reference.data[at + 1] - drawing.data[at + 1]) + Math.abs(reference.data[at + 2] - drawing.data[at + 2]);
5644
+ n++;
5645
+ }
5646
+ const error = n ? sum / n / 3 / 255 * 100 : 0;
5647
+ total += error;
5648
+ const ref = average(reference, x0, y0, x1, y1), art = average(drawing, x0, y0, x1, y1);
5649
+ cells.push({
5650
+ column,
5651
+ row,
5652
+ x: x0 / width,
5653
+ y: y0 / height,
5654
+ w: (x1 - x0) / width,
5655
+ h: (y1 - y0) / height,
5656
+ error: Math.round(error * 10) / 10,
5657
+ reference: hex(...ref),
5658
+ drawing: hex(...art),
5659
+ tone: Math.round((art[0] + art[1] + art[2] - ref[0] - ref[1] - ref[2]) / 3)
5660
+ });
5661
+ }
5662
+ cells.sort((a, b) => b.error - a.error);
5663
+ return {
5664
+ error: Math.round(total / cells.length * 10) / 10,
5665
+ worst: cells.slice(0, worst)
5666
+ };
5667
+ }
5668
+ function sampleColors(reference, drawing, points, radius = .004) {
5669
+ return points.map((point) => {
5670
+ const { width, height } = reference;
5671
+ const box = [
5672
+ (point.x - radius) * width,
5673
+ (point.y - radius) * height,
5674
+ (point.x + radius) * width,
5675
+ (point.y + radius) * height
5676
+ ];
5677
+ return {
5678
+ x: point.x,
5679
+ y: point.y,
5680
+ reference: hex(...average(reference, ...box)),
5681
+ drawing: hex(...average(drawing, ...box))
5682
+ };
5683
+ });
5684
+ }
5685
+ function dominantColors(picture, count) {
5686
+ const { data, width, height } = picture;
5687
+ const pixels = width * height, stride = Math.max(1, Math.floor(pixels / 2e4)), sample = [];
5688
+ for (let i = 0; i < pixels; i += stride) sample.push([
5689
+ data[i * 4],
5690
+ data[i * 4 + 1],
5691
+ data[i * 4 + 2]
5692
+ ]);
5693
+ const total = Math.min(count, sample.length);
5694
+ if (!total) return [];
5695
+ const mean = sample.reduce((sum, color) => [
5696
+ sum[0] + color[0],
5697
+ sum[1] + color[1],
5698
+ sum[2] + color[2]
5699
+ ], [
5700
+ 0,
5701
+ 0,
5702
+ 0
5703
+ ]).map((value) => value / sample.length);
5704
+ const centers = [mean];
5705
+ const nearest = sample.map((color) => (color[0] - mean[0]) ** 2 + (color[1] - mean[1]) ** 2 + (color[2] - mean[2]) ** 2);
5706
+ while (centers.length < total) {
5707
+ let at = 0;
5708
+ for (let i = 1; i < sample.length; i++) if (nearest[i] > nearest[at]) at = i;
5709
+ if (nearest[at] === 0) break;
5710
+ const center = sample[at].slice();
5711
+ centers.push(center);
5712
+ for (let i = 0; i < sample.length; i++) nearest[i] = Math.min(nearest[i], (sample[i][0] - center[0]) ** 2 + (sample[i][1] - center[1]) ** 2 + (sample[i][2] - center[2]) ** 2);
5713
+ }
5714
+ let sums = centers.map(() => [
5715
+ 0,
5716
+ 0,
5717
+ 0,
5718
+ 0
5719
+ ]);
5720
+ for (let round = 0; round < 8; round++) {
5721
+ sums = centers.map(() => [
5722
+ 0,
5723
+ 0,
5724
+ 0,
5725
+ 0
5726
+ ]);
5727
+ for (const color of sample) {
5728
+ let best = 0, bestDistance = Infinity;
5729
+ for (let c = 0; c < centers.length; c++) {
5730
+ const d = (color[0] - centers[c][0]) ** 2 + (color[1] - centers[c][1]) ** 2 + (color[2] - centers[c][2]) ** 2;
5731
+ if (d < bestDistance) {
5732
+ bestDistance = d;
5733
+ best = c;
5734
+ }
5735
+ }
5736
+ const sum = sums[best];
5737
+ sum[0] += color[0];
5738
+ sum[1] += color[1];
5739
+ sum[2] += color[2];
5740
+ sum[3]++;
5741
+ }
5742
+ sums.forEach((sum, c) => {
5743
+ if (sum[3]) centers[c] = [
5744
+ sum[0] / sum[3],
5745
+ sum[1] / sum[3],
5746
+ sum[2] / sum[3]
5747
+ ];
5748
+ });
5749
+ }
5750
+ return centers.map((center, c) => ({
5751
+ color: hex(...center),
5752
+ share: Math.round(sums[c][3] / sample.length * 1e3) / 10
5753
+ })).filter((item) => item.share > 0).sort((a, b) => b.share - a.share);
5754
+ }
5755
+ const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
5756
+ function scanLine(picture, line, { tolerance = 36, maxRuns = 40 } = {}) {
5757
+ const { data, width, height } = picture;
5758
+ const length = Math.max(2, Math.round(Math.hypot((line.x2 - line.x1) * width, (line.y2 - line.y1) * height)));
5759
+ const runs = [];
5760
+ let current;
5761
+ for (let i = 0; i <= length; i++) {
5762
+ const t = i / length, x = Math.min(width - 1, Math.max(0, Math.round((line.x1 + (line.x2 - line.x1) * t) * (width - 1))));
5763
+ const at = (Math.min(height - 1, Math.max(0, Math.round((line.y1 + (line.y2 - line.y1) * t) * (height - 1)))) * width + x) * 4, color = [
5764
+ data[at],
5765
+ data[at + 1],
5766
+ data[at + 2]
5767
+ ];
5768
+ if (current && distance(color, current.mean) <= tolerance) {
5769
+ current.to = t;
5770
+ current.n++;
5771
+ for (let k = 0; k < 3; k++) current.sum[k] += color[k];
5772
+ current.mean = current.sum.map((value) => value / current.n);
5773
+ } else {
5774
+ current = {
5775
+ from: t,
5776
+ to: t,
5777
+ n: 1,
5778
+ sum: [...color],
5779
+ mean: color
5780
+ };
5781
+ runs.push(current);
5782
+ }
5783
+ }
5784
+ const point = (t) => ({
5785
+ x: Math.round((line.x1 + (line.x2 - line.x1) * t) * 1e3) / 1e3,
5786
+ y: Math.round((line.y1 + (line.y2 - line.y1) * t) * 1e3) / 1e3
5787
+ });
5788
+ const merged = [];
5789
+ for (const run of runs) {
5790
+ if (merged.length && run.n < 3) {
5791
+ merged.at(-1).to = run.to;
5792
+ continue;
5793
+ }
5794
+ merged.push({ ...run });
5795
+ }
5796
+ return merged.slice(0, maxRuns).map((run) => ({
5797
+ from: point(run.from),
5798
+ to: point(run.to),
5799
+ color: hex(...run.mean)
5800
+ }));
5801
+ }
5802
+ function colorRegions(picture, count) {
5803
+ const colors = dominantColors(picture, count);
5804
+ if (!colors.length) return [];
5805
+ const { data, width, height } = picture;
5806
+ const centers = colors.map((item) => [
5807
+ 1,
5808
+ 3,
5809
+ 5
5810
+ ].map((at) => Number.parseInt(item.color.slice(at, at + 2), 16)));
5811
+ const xs = colors.map(() => []), ys = colors.map(() => []);
5812
+ const stride = Math.max(1, Math.floor(Math.sqrt(width * height / 4e4)));
5813
+ for (let y = 0; y < height; y += stride) for (let x = 0; x < width; x += stride) {
5814
+ const at = (y * width + x) * 4, pixel = [
5815
+ data[at],
5816
+ data[at + 1],
5817
+ data[at + 2]
5818
+ ];
5819
+ let best = 0, bestDistance = Infinity;
5820
+ for (let c = 0; c < centers.length; c++) {
5821
+ const d = distance(pixel, centers[c]);
5822
+ if (d < bestDistance) {
5823
+ bestDistance = d;
5824
+ best = c;
5825
+ }
5826
+ }
5827
+ xs[best].push(x / width);
5828
+ ys[best].push(y / height);
5829
+ }
5830
+ const cut = (values, share) => {
5831
+ values.sort((a, b) => a - b);
5832
+ return values[Math.min(values.length - 1, Math.floor(values.length * share))];
5833
+ };
5834
+ const round = (value) => Math.round(value * 1e3) / 1e3;
5835
+ return colors.map((item, c) => {
5836
+ if (!xs[c].length) return { ...item };
5837
+ const x0 = cut(xs[c], .02), x1 = cut(xs[c], .98), y0 = cut(ys[c], .02), y1 = cut(ys[c], .98);
5838
+ const cx = xs[c].reduce((sum, value) => sum + value, 0) / xs[c].length, cy = ys[c].reduce((sum, value) => sum + value, 0) / ys[c].length;
5839
+ return {
5840
+ ...item,
5841
+ center: {
5842
+ x: round(cx),
5843
+ y: round(cy)
5844
+ },
5845
+ box: {
5846
+ x: round(x0),
5847
+ y: round(y0),
5848
+ width: round(x1 - x0),
5849
+ height: round(y1 - y0)
5850
+ }
5851
+ };
5852
+ });
5853
+ }
5854
+ //#endregion
4418
5855
  //#region src/sketch-studio.jsx
4419
5856
  function SketchStudio({ open, agentEnabled, onOpen, onClose, attachSketch, enabled, t, incoming, sessionId, rpc, sessionState }) {
4420
5857
  const localSession = (0, react.useRef)(null);
4421
5858
  localSession.current ??= sessionState ?? createSketchSessionState();
4422
- const { doc, undo, redo, images, saved, dirty, documentId, documentRevision, agentAdapter, agentSession, agentRun } = localSession.current;
5859
+ const { doc, undo, redo, images, timeline, saved, dirty, documentId, documentRevision, agentAdapter, agentSession, agentRun } = localSession.current;
4423
5860
  const dialog = (0, react.useRef)(null), canvas = (0, react.useRef)(null), cache = (0, react.useRef)(/* @__PURE__ */ new Map());
4424
5861
  const active = (0, react.useRef)(null), frame = (0, react.useRef)(null), updateUi = (0, react.useRef)(false);
4425
5862
  const [agentState, setAgentState] = (0, react.useState)(agentRun.current?.state ?? "idle");
@@ -4475,6 +5912,7 @@ window.__ModuleLoader__.load({
4475
5912
  const [fillShape, setFillShape] = (0, react.useState)(false);
4476
5913
  const [hydrated, setHydrated] = (0, react.useState)(false), [recovered, setRecovered] = (0, react.useState)(false);
4477
5914
  const [restoreAttempt, retryRestore] = (0, react.useState)(0);
5915
+ const [replayOpen, setReplayOpen] = (0, react.useState)(false);
4478
5916
  const [layersOpen, setLayersOpen] = (0, react.useState)(false), [busy, setBusy] = (0, react.useState)(true), [error, setError] = (0, react.useState)("");
4479
5917
  const cursorRing = (0, react.useRef)(null);
4480
5918
  const cursor = useSketchCursor(canvas, cursorRing, width, tool === "pen" ? brush : "pen", navigation.view.scale, !open || navigation.space || busy || agentLocked || tool === "select" || tool === "text");
@@ -4503,6 +5941,7 @@ window.__ModuleLoader__.load({
4503
5941
  const checkpoint = () => {
4504
5942
  documentRevision.current++;
4505
5943
  dirty.current = true;
5944
+ recordReplayState(timeline.current, doc.current);
4506
5945
  undo.current.push(doc.current);
4507
5946
  if (undo.current.length > 30) undo.current.shift();
4508
5947
  redo.current = [];
@@ -4724,6 +6163,7 @@ window.__ModuleLoader__.load({
4724
6163
  id: layer.id,
4725
6164
  name: layer.name,
4726
6165
  visible: layer.visible,
6166
+ ...layer.blend ? { blend: layer.blend } : {},
4727
6167
  strokes: layer.strokes.length,
4728
6168
  image: Boolean(layer.image)
4729
6169
  })),
@@ -4759,6 +6199,88 @@ window.__ModuleLoader__.load({
4759
6199
  })
4760
6200
  });
4761
6201
  },
6202
+ pixels: ({ source, box = {
6203
+ x: 0,
6204
+ y: 0,
6205
+ width: 1,
6206
+ height: 1
6207
+ }, maxSide = 768 }) => {
6208
+ const layer = doc.current.layers.find((item) => source === void 0 ? item.image : item.id === source);
6209
+ const picture = layer?.image && images.current.get(layer.image.src);
6210
+ if (!picture) throw Error("There is no reference picture on the board; add one with the reference action first");
6211
+ const w = doc.current.width ?? 1024, h = doc.current.height ?? 1024;
6212
+ const scale = Math.min(1, maxSide / Math.max(box.width * w, box.height * h));
6213
+ const target = Object.assign(document.createElement("canvas"), {
6214
+ width: Math.max(1, Math.round(box.width * w * scale)),
6215
+ height: Math.max(1, Math.round(box.height * h * scale))
6216
+ });
6217
+ const context = target.getContext("2d", { willReadFrequently: true });
6218
+ context.fillStyle = "#ffffff";
6219
+ context.fillRect(0, 0, target.width, target.height);
6220
+ const at = layer.image;
6221
+ context.drawImage(picture, (at.x - box.x) * w * scale, (at.y - box.y) * h * scale, at.width * w * scale, at.height * h * scale);
6222
+ return context.getImageData(0, 0, target.width, target.height);
6223
+ },
6224
+ measure: async ({ columns, rows, cells = false, points, palette = 0, regions = 0, scan, box = {
6225
+ x: 0,
6226
+ y: 0,
6227
+ width: 1,
6228
+ height: 1
6229
+ } }) => {
6230
+ const reference = agentAdapter.current.pixels({
6231
+ box,
6232
+ maxSide: 480
6233
+ });
6234
+ const w = doc.current.width ?? 1024, h = doc.current.height ?? 1024;
6235
+ const scale = reference.width / (box.width * w);
6236
+ const whole = Object.assign(document.createElement("canvas"), {
6237
+ width: Math.max(1, Math.round(w * scale)),
6238
+ height: Math.max(1, Math.round(h * scale))
6239
+ });
6240
+ const drawn = {
6241
+ ...doc.current,
6242
+ layers: doc.current.layers.map((layer) => layer.image ? {
6243
+ ...layer,
6244
+ visible: false
6245
+ } : layer)
6246
+ };
6247
+ paintSketchLayers(whole.getContext("2d"), drawn, /* @__PURE__ */ new Map(), whole.width, whole.height, void 0, images.current);
6248
+ const target = Object.assign(document.createElement("canvas"), {
6249
+ width: reference.width,
6250
+ height: reference.height
6251
+ });
6252
+ const context = target.getContext("2d", { willReadFrequently: true });
6253
+ context.drawImage(whole, Math.round(box.x * whole.width), Math.round(box.y * whole.height), target.width, target.height, 0, 0, target.width, target.height);
6254
+ const drawing = context.getImageData(0, 0, target.width, target.height);
6255
+ return {
6256
+ ...measureDifference(reference, drawing, {
6257
+ columns,
6258
+ rows,
6259
+ ...cells ? { worst: columns * rows } : {}
6260
+ }),
6261
+ ...points.length ? { points: sampleColors(reference, drawing, points) } : {},
6262
+ ...palette ? { palette: dominantColors(reference, palette) } : {},
6263
+ ...regions ? { regions: colorRegions(reference, regions) } : {},
6264
+ ...scan ? { scan: {
6265
+ reference: scanLine(reference, scan),
6266
+ drawing: scanLine(drawing, scan)
6267
+ } } : {}
6268
+ };
6269
+ },
6270
+ undo: (steps = 1) => {
6271
+ let taken = 0;
6272
+ while (taken < steps && undo.current.length) {
6273
+ redo.current.push(doc.current);
6274
+ doc.current = undo.current.pop();
6275
+ taken++;
6276
+ }
6277
+ if (taken) {
6278
+ documentRevision.current++;
6279
+ dirty.current = true;
6280
+ schedule();
6281
+ }
6282
+ return taken;
6283
+ },
4762
6284
  addReference: async (dataUrl, name) => {
4763
6285
  const blob = await (await fetch(dataUrl)).blob();
4764
6286
  await importImage(new File([blob], name, { type: blob.type }), { visible: false });
@@ -4926,7 +6448,14 @@ window.__ModuleLoader__.load({
4926
6448
  hasContent: doc.current.layers.some((l) => l.visible && (l.image || l.strokes.length)),
4927
6449
  disabled: agentLocked || busy,
4928
6450
  t,
4929
- runOperation: runFile
6451
+ runOperation: runFile,
6452
+ extra: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
6453
+ type: "button",
6454
+ disabled: agentLocked || busy || !timeline.current.length,
6455
+ title: t("sketchReplayTitle"),
6456
+ onClick: () => setReplayOpen(true),
6457
+ children: t("sketchReplay")
6458
+ })
4930
6459
  }),
4931
6460
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4932
6461
  className: "codexSketchHeading",
@@ -5310,6 +6839,14 @@ window.__ModuleLoader__.load({
5310
6839
  change,
5311
6840
  t
5312
6841
  }) : null,
6842
+ replayOpen && dialog.current ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchReplay, {
6843
+ states: timeline.current,
6844
+ current: doc.current,
6845
+ images: images.current,
6846
+ name: saved.current?.name,
6847
+ onClose: () => setReplayOpen(false),
6848
+ t
6849
+ }), dialog.current) : null,
5313
6850
  layersOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SketchLayerPanel, {
5314
6851
  document: doc.current,
5315
6852
  disabled: agentLocked || busy,
@@ -5380,6 +6917,8 @@ window.__ModuleLoader__.load({
5380
6917
  .codexSketchDialog *{box-sizing:border-box}
5381
6918
  .codexSketchDialog button{font:inherit;color:inherit;border:0;background:transparent;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;flex-shrink:0}
5382
6919
  .codexSketchDialog button:disabled{opacity:.35;cursor:default}
6920
+ .codexSketchDialog .codexSketchConfirm:disabled{background:color-mix(in srgb,var(--sketch-fg) 12%,transparent);color:var(--sketch-muted);opacity:1}
6921
+ .codexSketchDialog .codexSketchSwatch::before{box-shadow:0 0 0 1px color-mix(in srgb,var(--sketch-fg) 28%,transparent)}
5383
6922
  .codexSketchDialog button:focus-visible,.codexSketchCustom:focus-within,.codexSketchDialog input:focus-visible{outline:2px solid #0a84ff;outline-offset:3px}
5384
6923
  .codexSketchTop{display:flex;align-items:center;justify-content:space-between;gap:8px}
5385
6924
  .codexSketchHeading{display:flex;align-items:center;gap:8px;flex:1}.codexSketchHeading strong{font-size:16px;font-weight:600}.codexSketchHeading>span{font-size:10px;color:var(--sketch-muted);border:1px solid var(--sketch-line);border-radius:6px;padding:1px 5px}
@@ -5428,6 +6967,22 @@ window.__ModuleLoader__.load({
5428
6967
  .codexSketchViewControls{display:flex;gap:2px;align-items:center}.codexSketchViewControls button{min-height:32px;padding:0 7px;border-radius:8px}.codexSketchKeyPanel{position:absolute;overflow:auto;overscroll-behavior:contain;padding:12px;border:1px solid var(--sketch-line);border-radius:14px;background:var(--sketch-bg);z-index:5;box-shadow:0 8px 30px #0003;scrollbar-width:thin}.codexSketchKeyPanel header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.codexSketchKeyPanel header button{width:28px;height:28px;border-radius:8px;font-size:20px}.codexSketchKeyPanel label{display:flex;align-items:center;justify-content:space-between;min-height:32px;gap:8px}.codexSketchKeysEnabled{padding-bottom:8px;border-bottom:1px solid var(--sketch-line)}.codexSketchKeysEnabled input{margin:0;accent-color:#0a84ff}.codexSketchKeyGrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 16px;margin:10px 0}.codexSketchKeyPanel input:not([type=checkbox]){width:52px;min-width:0;border:1px solid var(--sketch-line);border-radius:6px;color:inherit;background:color-mix(in srgb,var(--sketch-fg) 4%,transparent);padding:4px;text-align:center;font:inherit}.codexSketchKeyPanel p,.codexSketchKeyPanel small{display:block;color:var(--sketch-muted);font-size:11px;line-height:1.5;margin:0}.codexSketchKeyPanel small{border-top:1px solid var(--sketch-line);padding-top:8px}@media(max-width:380px){.codexSketchKeyGrid{grid-template-columns:1fr}}.codexSketchControls{position:static}
5429
6968
 
5430
6969
  .codexSketchCursor{position:fixed;left:0;top:0;z-index:100;pointer-events:none;border:1px solid #222;border-radius:50%;corner-shape:round;box-shadow:0 0 0 1px #fff;box-sizing:border-box}.codexSketchCursor[hidden]{display:none}
6970
+
6971
+ .codexSketchFiles{display:flex;gap:6px;align-items:center}.codexSketchFiles>button:disabled{opacity:.45}
6972
+ .codexSketchReplay{position:absolute;inset:0;z-index:20;display:flex;flex-direction:column;align-items:center;gap:12px;padding:14px 18px 16px;background:var(--sketch-bg);border-radius:inherit;overflow:hidden}
6973
+ .codexSketchReplay>header{display:flex;width:100%;align-items:center;justify-content:space-between;font-size:15px}
6974
+ .codexSketchDialog .codexSketchReplayClose{min-height:36px;padding:0 14px 0 10px;border-radius:18px;background:color-mix(in srgb,var(--sketch-fg) 7%,transparent);font-size:13px}
6975
+ .codexSketchReplayStage{flex:1;min-height:0;width:100%;display:flex;align-items:center;justify-content:center;container-type:size}
6976
+ .codexSketchReplayStage canvas,.codexSketchReplayStage video{max-width:100%;max-height:100%;border-radius:10px;background:#fff;box-shadow:0 0 0 1px var(--sketch-line),0 10px 36px #0002}
6977
+ .codexSketchReplayBar{display:flex;flex-wrap:wrap;width:100%;max-width:820px;align-items:center;justify-content:center;gap:10px;padding:8px 12px;border-radius:26px;background:color-mix(in srgb,var(--sketch-fg) 5%,transparent)}
6978
+ .codexSketchReplayBar input[type=range]{flex:1;min-width:140px;height:22px;accent-color:#0a84ff}
6979
+ .codexSketchDialog .codexSketchReplayBar>button{min-height:36px;padding:0 14px;border-radius:18px;background:color-mix(in srgb,var(--sketch-fg) 8%,transparent);font-size:13px}
6980
+ .codexSketchDialog .codexSketchReplayBar .codexSketchReplayPlay{width:40px;height:40px;min-height:40px;padding:0;border-radius:50%;background:#0a84ff;color:#fff}
6981
+ .codexSketchReplayTime{min-width:78px;font-variant-numeric:tabular-nums;color:var(--sketch-muted);font-size:12px}
6982
+ .codexSketchReplayRecord i{width:10px;height:10px;border-radius:50%;background:#ff3b30}
6983
+ .codexSketchDialog .codexSketchReplayRecord[data-recording]{background:#ff3b30;color:#fff}.codexSketchReplayRecord[data-recording] i{background:#fff;border-radius:2px}
6984
+ .codexSketchReplay small{color:var(--sketch-muted);text-align:center}
6985
+ .codexSketchReplaySave{display:inline-flex;align-items:center;min-height:36px;padding:0 18px;border-radius:18px;background:#0a84ff;color:#fff;font-size:13px;font-weight:600;text-decoration:none}
5431
6986
  `;
5432
6987
  //#endregion
5433
6988
  //#region src/sketch-workspace.jsx
@@ -5499,7 +7054,7 @@ window.__ModuleLoader__.load({
5499
7054
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [settings.imageSketch && settings.imageEditing ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Tooltip, {
5500
7055
  label: t("sketch"),
5501
7056
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
5502
- variant: "toolbar",
7057
+ variant: "ghost",
5503
7058
  size: "sm",
5504
7059
  "aria-label": t("sketch"),
5505
7060
  onClick: (event) => workspace.current?.("sketch", event.currentTarget),
@@ -5634,7 +7189,7 @@ window.__ModuleLoader__.load({
5634
7189
  storageTitle: "存储与缓存",
5635
7190
  storageForecast: "额度预测缓存",
5636
7191
  storageClear: "清除预测历史",
5637
- storageHint: "仅清理本地预测历史,保留原图、草稿、登录信息和共享依赖。子任务组件可在“模型与运行”中管理。",
7192
+ storageHint: "只清理本地预测历史;原图、草稿、登录信息和共享依赖不受影响。子任务组件在“与其他模型”中管理。",
5638
7193
  storageConfirm: "清除所有已登录账号的本地预测历史后,需要重新积累采样。服务端额度不变,后续查询会重新生成缓存。",
5639
7194
  storageFailed: "未能读取或清除预测缓存,请重试。",
5640
7195
  runtimeIncompatible: "检测到不兼容的 Codex 子任务组件,请卸载后重启,再安装受支持版本。",
@@ -5661,7 +7216,11 @@ window.__ModuleLoader__.load({
5661
7216
  compactionTitle: "云端压缩",
5662
7217
  compaction_dsh: "关闭",
5663
7218
  compaction_cloud: "开启",
5664
- compactionHint: "实验功能,默认关闭。长上下文由 Codex 压缩后继续请求,保留 DSH 历史与原生压缩。开启时该请求使用 SSE;历史改变后重新建立压缩状态。",
7219
+ compactionHint: "长上下文由 Codex 压缩后继续请求,保留 DSH 历史与原生压缩。开启时该请求使用 SSE;历史改变后重新建立压缩状态。",
7220
+ otherModelsTitle: "在 DeepSeek 等其他模型的对话里使用订阅功能",
7221
+ otherModels_on: "开",
7222
+ otherModels_off: "关",
7223
+ otherModelsHint: "关闭后,用 DeepSeek 等非 Codex 模型对话时不再使用订阅的联网搜索(改用 DSH 搜索)、图片生成和 ChatGPT 连接器;Codex 订阅模型不受影响。手机远程控制和语音对话由你主动开启或发起,不受这个开关影响,可在本页单独设置。",
5665
7224
  advancedModelSearch: "模型与搜索",
5666
7225
  modelsSectionTitle: "模型",
5667
7226
  searchSectionTitle: "搜索",
@@ -5708,13 +7267,54 @@ window.__ModuleLoader__.load({
5708
7267
  subagentBackend_dsh: "DSH",
5709
7268
  subagentBackend_codex: "Codex",
5710
7269
  connectionTitle: "连接方式",
7270
+ diagnosticsLog: "运行日志",
7271
+ diagnosticsLogHint: "按时间记录运行中发生的事,错误和警告在最上面的筛选里。内容已去掉令牌、邮箱和路径。",
7272
+ logLevel_all: "全部",
7273
+ logLevel_warn: "警告和错误",
7274
+ logLevel_error: "仅错误",
7275
+ logEmpty: "这个级别暂时没有记录。",
7276
+ logCopy: "复制日志",
7277
+ logCopied: "已复制日志",
7278
+ logEarlier: "上次运行",
5711
7279
  remoteTitle: "手机远程控制",
5712
7280
  remote_off: "关闭",
5713
7281
  remote_on: "开启",
5714
- remoteHint: "实验功能,默认关闭。开启后,这台电脑上的 DSH 会出现在 ChatGPT 手机 App 的 Codex 主机列表里,可用手机查看对话、发消息、切换模型和审批。需要订阅账号登录;电脑要保持开机和联网。",
5715
- remoteConnected: "已连接",
7282
+ voiceStart: "语音对话",
7283
+ voiceEnd: "结束语音",
7284
+ voiceConnecting: "正在连接语音…",
7285
+ voiceListening: "在听",
7286
+ voiceSpeaking: "在说",
7287
+ voiceWorking: "DSH 正在处理…",
7288
+ voiceMute: "关闭麦克风",
7289
+ voiceUnmute: "打开麦克风",
7290
+ voiceMuteSpeaker: "关闭声音",
7291
+ voiceUnmuteSpeaker: "打开声音",
7292
+ voiceMicBlocked: "没有麦克风权限,请在浏览器或系统里允许后再试。",
7293
+ voiceFailed: "语音没有接通,请稍后再试。",
7294
+ voiceTitle: "语音对话",
7295
+ voiceHint: "输入框里没有内容时,发送键变成语音键:点一下就能和 DSH 说话,让它做事,它的回答会念出来。语音通话由 ChatGPT 订阅提供,通话内容会经过 OpenAI。",
7296
+ voiceVoice: "音色",
7297
+ voiceLanguage: "回答语言",
7298
+ voiceAuto: "跟你说的语言一致",
7299
+ voicePlay: "试听",
7300
+ voiceLoading: "加载中…",
7301
+ voiceNoSample: "这个音色暂时没有试听样本。",
7302
+ voiceUnavailable: "暂无试听",
7303
+ voiceMore: "更多音色(暂无试听)",
7304
+ voiceLang_zh: "中文",
7305
+ voiceLang_en: "English",
7306
+ voiceLang_ja: "日本語",
7307
+ voiceLang_ko: "한국어",
7308
+ voiceLang_es: "Español",
7309
+ voiceLang_fr: "Français",
7310
+ voiceLang_de: "Deutsch",
7311
+ voiceLang_pt: "Português",
7312
+ voiceLang_ru: "Русский",
7313
+ remoteHint: "开启后,这台电脑上的 DSH 会出现在 ChatGPT 手机 App 的 Codex 主机列表里,可用手机查看对话、发消息、切换模型和审批。需要订阅账号登录;电脑要保持开机和联网。",
7314
+ remoteConnected: "电脑已连上 ChatGPT,还没有手机连接",
5716
7315
  remoteConnecting: "正在连接",
5717
7316
  remoteWaiting: "正在等待上一次连接释放,通常几分钟内自动连上",
7317
+ remoteConflictLong: "长时间连不上,通常是另一台电脑、另一份 DSH(或另一个窗口)也在用同一个 ChatGPT 账号开着手机远程,彼此在抢连接。请关闭其他地方的手机远程,再回到这里点“关闭”后重新“开启”。",
5718
7318
  remoteError: "连接失败,会自动重试",
5719
7319
  remoteStopped: "已停止",
5720
7320
  remotePaired: "已配对的手机",
@@ -5722,7 +7322,7 @@ window.__ModuleLoader__.load({
5722
7322
  remoteRevoke: "移除",
5723
7323
  remoteLastSeen: "最近 {date}",
5724
7324
  remotePhoneUnknown: "未命名手机",
5725
- remotePhones: "{count} 个手机连接",
7325
+ remotePhones: "手机已连接 {count} 部",
5726
7326
  remotePair: "显示配对码",
5727
7327
  remotePairAgain: "重新生成配对码",
5728
7328
  remotePairFailed: "无法生成配对码,请确认已登录订阅账号。",
@@ -5735,7 +7335,7 @@ window.__ModuleLoader__.load({
5735
7335
  reviewModelTitle: "Auto review 审查模型",
5736
7336
  reviewModel_session: "当前模型",
5737
7337
  reviewModel_official: "Codex 官方审查模型",
5738
- reviewModelHint: "实验功能,默认使用当前模型。选择官方后,DSH Auto review 用 Codex 自带的审查模型判断工具调用(账号目录提供时),审查规则与放行、拒绝流程仍由 DSH 负责;不可用时沿用当前模型。",
7338
+ reviewModelHint: "默认使用当前模型。选择官方后,DSH Auto review 用 Codex 自带的审查模型判断工具调用(账号目录提供时),审查规则与放行、拒绝流程仍由 DSH 负责;不可用时沿用当前模型。",
5739
7339
  connectionHint: "默认 SSE。WebSocket 实验性复用连接与上下文传输;连接失败可回退 SSE。下次请求生效,不扩大上下文容量。",
5740
7340
  streamIdleTimeoutTitle: "流无响应超时",
5741
7341
  streamIdleTimeoutHint: "连续多久没有收到任何流式数据时中断本次请求,不是整体回答时限。调低可能中断较慢但仍在推理的回答,并交由 DSH 重试处理。默认 10 分钟。",
@@ -5814,6 +7414,24 @@ window.__ModuleLoader__.load({
5814
7414
  sketchKey_zoomIn: "放大",
5815
7415
  sketchKey_zoomOut: "缩小",
5816
7416
  sketchKey_fit: "重置视图",
7417
+ sketchReplay: "回放",
7418
+ sketchReplayTitle: "绘制过程",
7419
+ sketchReplayClose: "返回",
7420
+ sketchReplayPlay: "播放",
7421
+ sketchReplayPause: "暂停",
7422
+ sketchReplaySpeed: "回放时长",
7423
+ sketchReplayFast: "12 秒",
7424
+ sketchReplayNormal: "30 秒",
7425
+ sketchReplaySlow: "60 秒",
7426
+ sketchReplayRecord: "录制过程视频",
7427
+ sketchReplaySave: "保存视频",
7428
+ sketchReplayAgain: "回到回放",
7429
+ sketchReplaySaveHint: "点「保存视频」时,系统会让你选择保存位置。",
7430
+ sketchReplayStopRecording: "停止录制",
7431
+ sketchReplayEmpty: "还没有可回放的绘制。",
7432
+ sketchReplayUnsupported: "当前环境不支持录制视频。",
7433
+ sketchReplayFileSuffix: "过程",
7434
+ sketchReplayHint: "按落笔顺序重放整幅画;录制会把回放生成 WebM 视频(按所选时长实时录制),录完先在这里预览,再决定是否保存。",
5817
7435
  sketchFiles: "草稿",
5818
7436
  sketchNew: "新建草图",
5819
7437
  sketchImport: "导入文件",
@@ -6024,9 +7642,9 @@ window.__ModuleLoader__.load({
6024
7642
  searchTitle: "搜索来源",
6025
7643
  searchScope: "自动按当前会话模型分流;手动选择会覆盖所有模型和会话。",
6026
7644
  searchAuto: "自动",
6027
- searchAutoHint: "Codex 模型用订阅搜索,其他模型用 DSH",
7645
+ searchAutoHint: "Codex 模型用订阅搜索,其他模型用 DSH;一方未登录或没有 Key 时自动改用另一方。",
6028
7646
  searchDsh: "DSH 默认",
6029
- searchDshHint: "所有模型使用 DSH 当前搜索服务",
7647
+ searchDshHint: "所有模型使用 DSH 当前搜索服务;没有 API Key 时用已登录的 DeepSeek 账号",
6030
7648
  searchCodex: "Codex 订阅",
6031
7649
  searchCodexHint: "所有模型通过已登录的 ChatGPT 订阅搜索",
6032
7650
  preferenceFailed: "设置未保存。",
@@ -6145,7 +7763,7 @@ window.__ModuleLoader__.load({
6145
7763
  quickQuotaForecast: "续航预测",
6146
7764
  quickQuotaBeta: "Beta",
6147
7765
  autoQuotaRetry: "额度重置后自动重试",
6148
- autoQuotaRetryHint: "选择开启后,将等待已确认的短时额度重置;对话会显示等待原因且可停止,等待期间切换账号会立即重试。",
7766
+ autoQuotaRetryHint: "开启后,等待已确认的短时额度重置;对话会显示等待原因且可停止,等待期间切换账号会立即重试。",
6149
7767
  quickQuotaForecastHint: "按最近两小时的消耗估算;消耗不足或速度突变时重新校准,详情显示估计范围。仅供参考,历史保存在本机。",
6150
7768
  contextTitle: "上下文窗口",
6151
7769
  contextStandard: "标准",
@@ -6160,9 +7778,10 @@ window.__ModuleLoader__.load({
6160
7778
  settingsTab_account: "账号与额度",
6161
7779
  settingsTab_display: "使用偏好",
6162
7780
  settingsTab_advanced: "模型与运行",
7781
+ settingsTab_interop: "与其他模型",
6163
7782
  settingsTab_creative: "图片与草图",
6164
7783
  settingsTab_maintenance: "维护",
6165
- creativeSketch: "草图画板",
7784
+ creativeSketch: "草图画板 · Beta",
6166
7785
  diagnosticsHint: "遇到问题时生成报告,可复制后用于反馈。不含登录凭据和账号标识。",
6167
7786
  sketchCanvasSetting: "画板入口",
6168
7787
  sketchAgentSetting: "Agent 绘图",
@@ -6320,7 +7939,7 @@ window.__ModuleLoader__.load({
6320
7939
  storageTitle: "Storage and cache",
6321
7940
  storageForecast: "Quota forecast cache",
6322
7941
  storageClear: "Clear forecast history",
6323
- storageHint: "Clears local forecast history only. Original images, drafts, sign-in data and shared dependencies are preserved. Manage subtask components under Models & runtime.",
7942
+ storageHint: "Clears local forecast history only; original images, drafts, sign-in data and shared dependencies are untouched. Subtask components are managed under Other models.",
6324
7943
  storageConfirm: "This clears local forecast samples for all signed-in accounts. Forecasts will need new samples. Server quotas stay unchanged; subsequent checks recreate the cache.",
6325
7944
  storageFailed: "Could not read or clear the forecast cache. Try again.",
6326
7945
  runtimeIncompatible: "An incompatible Codex subtask component was found. Uninstall it, restart DSH, then install the supported version.",
@@ -6347,7 +7966,11 @@ window.__ModuleLoader__.load({
6347
7966
  compactionTitle: "Cloud compaction",
6348
7967
  compaction_dsh: "Off",
6349
7968
  compaction_cloud: "On",
6350
- compactionHint: "Experimental, off by default. Codex compacts long requests while DSH history and native compaction remain available. These requests use SSE; changed history invalidates previous checkpoints.",
7969
+ compactionHint: "Codex compacts long requests while DSH history and native compaction remain available. These requests use SSE; changed history invalidates previous checkpoints.",
7970
+ otherModelsTitle: "Use subscription features in conversations on other models (DeepSeek, …)",
7971
+ otherModels_on: "On",
7972
+ otherModels_off: "Off",
7973
+ otherModelsHint: "When off, conversations on DeepSeek and other non-Codex models no longer use subscription web search (DSH search is used instead), image generation or ChatGPT connectors; Codex subscription models are not affected. Phone remote control and voice calls are started by you and are not affected by this switch; set them separately on this page.",
6351
7974
  advancedModelSearch: "Models and search",
6352
7975
  modelsSectionTitle: "Models",
6353
7976
  searchSectionTitle: "Search",
@@ -6394,13 +8017,54 @@ window.__ModuleLoader__.load({
6394
8017
  subagentBackend_dsh: "DSH",
6395
8018
  subagentBackend_codex: "Codex",
6396
8019
  connectionTitle: "Connection",
8020
+ diagnosticsLog: "Log",
8021
+ diagnosticsLogHint: "What happened while running, in order. Filter to warnings and errors above. Tokens, emails and paths are removed.",
8022
+ logLevel_all: "All",
8023
+ logLevel_warn: "Warnings and errors",
8024
+ logLevel_error: "Errors only",
8025
+ logEmpty: "Nothing recorded at this level yet.",
8026
+ logCopy: "Copy log",
8027
+ logCopied: "Log copied",
8028
+ logEarlier: "previous run",
6397
8029
  remoteTitle: "Phone remote control",
6398
8030
  remote_off: "Off",
6399
8031
  remote_on: "On",
6400
- remoteHint: "Experimental, off by default. When on, this computer's DSH appears as a host in the ChatGPT mobile app's Codex list, so you can follow conversations, send messages, switch models and approve actions from your phone. Needs a signed-in subscription account; the computer must stay on and online.",
6401
- remoteConnected: "Connected",
8032
+ voiceStart: "Voice conversation",
8033
+ voiceEnd: "End voice",
8034
+ voiceConnecting: "Connecting voice…",
8035
+ voiceListening: "Listening",
8036
+ voiceSpeaking: "Speaking",
8037
+ voiceWorking: "DSH is working on it…",
8038
+ voiceMute: "Turn the microphone off",
8039
+ voiceUnmute: "Turn the microphone on",
8040
+ voiceMuteSpeaker: "Turn the sound off",
8041
+ voiceUnmuteSpeaker: "Turn the sound on",
8042
+ voiceMicBlocked: "No microphone permission: allow it in the browser or system and try again.",
8043
+ voiceFailed: "The voice call did not connect. Try again in a moment.",
8044
+ voiceTitle: "Voice conversation",
8045
+ voiceHint: "When the message box is empty, the send button becomes a voice button: tap it to talk to DSH, ask it to do things, and hear the answer. Calls use your ChatGPT subscription and go through OpenAI.",
8046
+ voiceVoice: "Voice",
8047
+ voiceLanguage: "Answer language",
8048
+ voiceAuto: "Same as you speak",
8049
+ voicePlay: "Listen",
8050
+ voiceLoading: "Loading…",
8051
+ voiceNoSample: "No sample is available for this voice.",
8052
+ voiceUnavailable: "no sample yet",
8053
+ voiceMore: "More voices (no sample yet)",
8054
+ voiceLang_zh: "中文",
8055
+ voiceLang_en: "English",
8056
+ voiceLang_ja: "日本語",
8057
+ voiceLang_ko: "한국어",
8058
+ voiceLang_es: "Español",
8059
+ voiceLang_fr: "Français",
8060
+ voiceLang_de: "Deutsch",
8061
+ voiceLang_pt: "Português",
8062
+ voiceLang_ru: "Русский",
8063
+ remoteHint: "When on, this computer's DSH appears as a host in the ChatGPT mobile app's Codex list, so you can follow conversations, send messages, switch models and approve actions from your phone. Needs a signed-in subscription account; the computer must stay on and online.",
8064
+ remoteConnected: "This computer is online with ChatGPT; no phone connected yet",
6402
8065
  remoteConnecting: "Connecting",
6403
8066
  remoteWaiting: "Waiting for the previous connection to be released; usually reconnects within a few minutes",
8067
+ remoteConflictLong: "Still not connecting? Usually another computer, another DSH copy or another window is using phone remote control with the same ChatGPT account and they keep taking the connection from each other. Turn phone remote control off elsewhere, then switch it Off and On again here.",
6404
8068
  remoteError: "Connection failed, retrying",
6405
8069
  remoteStopped: "Stopped",
6406
8070
  remotePaired: "Paired phones",
@@ -6421,7 +8085,7 @@ window.__ModuleLoader__.load({
6421
8085
  reviewModelTitle: "Auto review model",
6422
8086
  reviewModel_session: "Current model",
6423
8087
  reviewModel_official: "Codex reviewer",
6424
- reviewModelHint: "Experimental; uses the current model by default. With Codex reviewer, DSH Auto review judges tool calls with Codex's own review model when your account catalog offers it. DSH keeps its review policy and allow/deny flow; otherwise the current model is used.",
8088
+ reviewModelHint: "Uses the current model by default. With Codex reviewer, DSH Auto review judges tool calls with Codex's own review model when your account catalog offers it. DSH keeps its review policy and allow/deny flow; otherwise the current model is used.",
6425
8089
  connectionHint: "SSE by default. Experimental WebSocket reuses connections and context transfers and can fall back to SSE on connection failure. Applies to the next request; context limits stay the same.",
6426
8090
  streamIdleTimeoutTitle: "Stream inactivity timeout",
6427
8091
  streamIdleTimeoutHint: "How long a request may receive no streamed data before it is aborted. This is not an overall response deadline. Lower values can abort slow but valid reasoning and hand the request to DSH retry handling. Default: 10 minutes.",
@@ -6500,6 +8164,24 @@ window.__ModuleLoader__.load({
6500
8164
  sketchKey_zoomIn: "Zoom in",
6501
8165
  sketchKey_zoomOut: "Zoom out",
6502
8166
  sketchKey_fit: "Reset view",
8167
+ sketchReplay: "Replay",
8168
+ sketchReplayTitle: "How it was drawn",
8169
+ sketchReplayClose: "Back",
8170
+ sketchReplayPlay: "Play",
8171
+ sketchReplayPause: "Pause",
8172
+ sketchReplaySpeed: "Replay length",
8173
+ sketchReplayFast: "12 s",
8174
+ sketchReplayNormal: "30 s",
8175
+ sketchReplaySlow: "60 s",
8176
+ sketchReplayRecord: "Record process video",
8177
+ sketchReplaySave: "Save video",
8178
+ sketchReplayAgain: "Back to replay",
8179
+ sketchReplaySaveHint: "Choosing Save video asks where to put the file.",
8180
+ sketchReplayStopRecording: "Stop recording",
8181
+ sketchReplayEmpty: "Nothing to replay yet.",
8182
+ sketchReplayUnsupported: "Video recording is not available here.",
8183
+ sketchReplayFileSuffix: "process",
8184
+ sketchReplayHint: "Replays the drawing stroke by stroke; recording turns the replay into a WebM video (in real time, at the chosen length) that you can preview here before saving it.",
6503
8185
  sketchFiles: "Drafts",
6504
8186
  sketchNew: "New sketch",
6505
8187
  sketchImport: "Import file",
@@ -6710,9 +8392,9 @@ window.__ModuleLoader__.load({
6710
8392
  searchTitle: "Search source",
6711
8393
  searchScope: "Auto follows the current session model; an explicit choice overrides every model and session.",
6712
8394
  searchAuto: "Auto",
6713
- searchAutoHint: "Codex models use subscription search; other models use DSH",
8395
+ searchAutoHint: "Codex models use subscription search; other models use DSH; if one side is not signed in or has no key, the other is used.",
6714
8396
  searchDsh: "DSH default",
6715
- searchDshHint: "Use DSH's current search service for every model",
8397
+ searchDshHint: "Use DSH's current search service for every model; without an API key the signed-in DeepSeek account is used",
6716
8398
  searchCodex: "Codex subscription",
6717
8399
  searchCodexHint: "Search through the signed-in ChatGPT subscription for every model",
6718
8400
  preferenceFailed: "The setting was not saved.",
@@ -6831,7 +8513,7 @@ window.__ModuleLoader__.load({
6831
8513
  quickQuotaForecast: "Runway",
6832
8514
  quickQuotaBeta: "Beta",
6833
8515
  autoQuotaRetry: "Retry after quota reset",
6834
- autoQuotaRetryHint: "Opt in to wait for confirmed short quota resets. The turn shows why it is waiting and can be stopped; switching accounts retries immediately.",
8516
+ autoQuotaRetryHint: "Wait for confirmed short quota resets. The turn shows why it is waiting and can be stopped; switching accounts retries immediately.",
6835
8517
  quickQuotaForecastHint: "Estimates recent two-hour consumption; recalibrates with insufficient data or changing pace. Details show a range. Indicative only; history stays local.",
6836
8518
  contextTitle: "Context window",
6837
8519
  contextStandard: "Standard",
@@ -6846,9 +8528,10 @@ window.__ModuleLoader__.load({
6846
8528
  settingsTab_account: "Account",
6847
8529
  settingsTab_display: "Preferences",
6848
8530
  settingsTab_advanced: "Models & runtime",
8531
+ settingsTab_interop: "Other models",
6849
8532
  settingsTab_creative: "Images & sketch",
6850
8533
  settingsTab_maintenance: "Maintenance",
6851
- creativeSketch: "Sketch board",
8534
+ creativeSketch: "Sketch board · Beta",
6852
8535
  diagnosticsHint: "Generate a report to copy into a support request. Sign-in credentials and account identifiers are excluded.",
6853
8536
  sketchCanvasSetting: "Board entry",
6854
8537
  sketchAgentSetting: "Agent drawing",
@@ -6943,6 +8626,7 @@ window.__ModuleLoader__.load({
6943
8626
  //#region src/client-styles.js
6944
8627
  const STYLE = `
6945
8628
  .codexSubscriptionAdvancedPreferences{display:flex;flex-direction:column;gap:10px}
8629
+ .codexSubscriptionAdvancedPreferences[data-others-off=true]>[data-governed=true]{opacity:.55;transition:opacity .15s}
6946
8630
  .codexSubscriptionSearchChoices.codexSubscriptionQuotaModes{display:flex;flex:0 0 auto;gap:0;grid-template-columns:none}
6947
8631
  .codexSubscriptionSettingsDisclosure>summary{display:flex;align-items:center;gap:10px;min-height:28px;cursor:pointer;list-style:none;font-size:14px;font-weight:500}
6948
8632
  .codexSubscriptionSettingsDisclosure>summary::-webkit-details-marker{display:none}
@@ -6979,8 +8663,8 @@ window.__ModuleLoader__.load({
6979
8663
  .codexSubscriptionPreferenceLabel{display:flex;align-items:center;gap:6px}
6980
8664
  .codexSubscriptionPreference>.codexSubscriptionPreferenceCopy{flex:1 1 240px}
6981
8665
  .codexSubscriptionPreferenceHint{max-width:none;font-size:11px;line-height:17px;color:var(--dsw-alias-label-tertiary)}
6982
- .codexSubscriptionHintText{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}
6983
- .codexSubscriptionHintFold[data-open=true] .codexSubscriptionHintText{display:block;-webkit-line-clamp:unset}
8666
+ .codexSubscriptionHintText{display:block}
8667
+ .codexSubscriptionHintFold[data-fold=true] .codexSubscriptionHintText{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden}
6984
8668
  .codexSubscriptionHintToggle{display:inline-flex;align-items:center;gap:3px;margin-top:2px;padding:0;border:0;background:none;font:inherit;font-size:11px;line-height:17px;color:var(--dsw-alias-label-secondary);cursor:pointer}
6985
8669
  .codexSubscriptionHintToggle::after{content:"";width:5px;height:5px;margin-top:-2px;border:solid currentColor;border-width:0 1.5px 1.5px 0;transform:rotate(45deg);transition:transform .15s}
6986
8670
  .codexSubscriptionHintFold[data-open=true] .codexSubscriptionHintToggle::after{margin-top:2px;transform:rotate(-135deg)}
@@ -7018,7 +8702,7 @@ window.__ModuleLoader__.load({
7018
8702
  .codexSubscriptionContextModelCopy strong{font-size:12px;line-height:18px;font-weight:500}
7019
8703
  .codexSubscriptionContextModelCopy span{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
7020
8704
  .codexSubscriptionContextInput{width:116px}
7021
- .codexSubscriptionSearch{display:flex;flex-direction:column;gap:7px}
8705
+ .codexSubscriptionSearch{display:flex;flex-direction:column;gap:2px}
7022
8706
  .codexSubscriptionDivider{height:1px;background:var(--dsw-alias-border-l2)}
7023
8707
  .codexSubscriptionQuotaModes[data-saving=true] .codexSubscriptionQuotaMode:has(input:disabled){cursor:wait;opacity:1}
7024
8708
  .codexSubscriptionSearchChoices[data-saving=true] .codexSubscriptionQuotaMode:has(input:disabled){cursor:wait;opacity:1}
@@ -7094,7 +8778,7 @@ window.__ModuleLoader__.load({
7094
8778
  .codexSubscriptionLimit progress::-moz-progress-bar{background:var(--dsw-alias-brand-primary,#3964fe);border-radius:999px}
7095
8779
  .codexSubscriptionLimitMeta{display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;font-size:11px;line-height:17px;color:var(--dsw-alias-label-tertiary)}
7096
8780
  .codexSubscriptionLimitPeriod{display:flex;gap:8px;flex-wrap:wrap}
7097
- .codexSubscriptionSearchOptions{margin-top:10px;font-size:12px}
8781
+ .codexSubscriptionSearch>.codexSubscriptionSearchOptions{margin-top:0;padding-top:2px;border-top:1px solid var(--dsw-alias-border-l2);font-size:12px}
7098
8782
  .codexSubscriptionDivider+.codexSubscriptionDivider{display:none}
7099
8783
  .codexSubscriptionPickerModels{display:flex;flex-direction:column;border-top:1px solid var(--dsw-alias-border-l2)}
7100
8784
  .codexSubscriptionPickerModel{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:36px;border-bottom:1px solid var(--dsw-alias-border-l2);font-size:13px}
@@ -7152,7 +8836,7 @@ window.__ModuleLoader__.load({
7152
8836
  .codexSubscriptionSpendLimit progress::-webkit-progress-bar{background:var(--dsw-alias-border-l3);border-radius:999px}
7153
8837
  .codexSubscriptionSpendLimit progress::-webkit-progress-value{background:var(--dsw-alias-brand-primary,#3964fe);border-radius:999px}
7154
8838
  .codexSubscriptionSpendLimit progress::-moz-progress-bar{background:var(--dsw-alias-brand-primary,#3964fe);border-radius:999px}
7155
- .codexSettingsTabs{position:sticky;top:0;z-index:2;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;padding:4px;background:var(--dsw-alias-bg-module-platform);border-radius:12px}
8839
+ .codexSettingsTabs{position:sticky;top:0;z-index:2;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px;padding:4px;background:var(--dsw-alias-bg-module-platform);border-radius:12px}
7156
8840
  .codexSettingsTabs button{min-width:0;min-height:36px;border:0;border-radius:9px;padding:7px 6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer}
7157
8841
  .codexSettingsTabs button:focus-visible{outline:2px solid var(--dsw-alias-border-l3);outline-offset:1px}
7158
8842
  .codexSettingsTabs button[aria-selected=true]{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);box-shadow:0 1px 3px #0001}
@@ -7253,8 +8937,61 @@ window.__ModuleLoader__.load({
7253
8937
  .codexSubscriptionRuntime{padding-top:10px;border-top:1px solid var(--dsw-alias-border-l2);margin-top:2px}
7254
8938
  .codexSubscriptionRuntime details{margin-top:8px}.codexSubscriptionRuntime details[open]>summary{margin-bottom:10px}
7255
8939
  @container (max-width:480px){.codexSubscriptionPreference,.codexSubscriptionContextHead{flex-wrap:wrap}.codexSubscriptionPreferenceHint{max-width:none}.codexSubscriptionPreference>.codexSubscriptionPreferenceCopy{flex:1 1 220px}.codexSubscriptionQuotaModes{max-width:100%;flex-wrap:wrap}.codexSubscriptionQuotaMode{min-height:30px}.codexSubscriptionActions{flex-wrap:wrap}}
7256
- @container (max-width:340px){.codexSettingsTabs{grid-template-columns:repeat(2,minmax(0,1fr))}}
8940
+ @container (max-width:420px){.codexSettingsTabs{grid-template-columns:none;grid-auto-flow:column;grid-auto-columns:minmax(max-content,1fr);overflow-x:auto;scrollbar-width:none}.codexSettingsTabs button{padding:7px 10px;white-space:nowrap}}
7257
8941
  @media(prefers-reduced-motion:reduce){.codexSubscription *{transition:none!important}}
8942
+ .codexSubscriptionLogHead{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin-top:12px}.codexSubscriptionLogHead h4{margin:0;font-size:13px}.codexSubscriptionLog{max-height:320px;overflow:auto;margin:6px 0 0;padding:8px 10px;border:1px solid var(--border,#0002);border-radius:8px;font:11.5px/1.5 ui-monospace,Consolas,monospace;white-space:pre-wrap;word-break:break-word}.codexSubscriptionLog_error{color:#c0392b}.codexSubscriptionLog_warn{color:#b9770e}.codexSubscriptionLog_info{opacity:.8}
8943
+ .codexSubscriptionConnectors>.codexSubscriptionQuotaModes{flex:0 0 auto;display:flex;flex-wrap:nowrap;margin-left:auto}
8944
+ .codexSubscriptionConnectors .codexSubscriptionQuotaMode{min-height:28px;padding:0 10px;white-space:nowrap}
8945
+ .codexSubscriptionConnectors>.codexSubscriptionModeNote{padding:0;background:none;font-size:12px;line-height:18px}
8946
+ .codexSubscriptionConnectors>.codexSubscriptionModeNote[data-danger=true]{background:none}
8947
+ @container (max-width:520px){.codexSubscriptionConnectors>.codexSubscriptionQuotaModes{flex:1 1 100%;margin-left:0;display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr)}.codexSubscriptionConnectors .codexSubscriptionQuotaMode{padding:0 4px;white-space:normal;text-align:center}}
8948
+ .codexVoiceChoice{display:flex;align-items:center;gap:8px}
8949
+ .codexVoiceChoice .codexSubscriptionContextTrigger{min-width:150px;justify-content:space-between}
8950
+ .codexVoiceChoice .codexSubscriptionContextTrigger:first-child:not(:last-child){min-width:0;justify-content:center}
8951
+ /* The voice button wears the send button's own classes, so its colours, shape and theme are always the send button's. */
8952
+ .codexVoiceCall{position:absolute;z-index:2;margin:0}
8953
+ .codexVoiceCall:disabled{cursor:progress}
8954
+ .codexVoiceCall[data-state=connecting]{animation:codexVoicePulse 1.1s ease-in-out infinite}
8955
+ .codexVoiceCallNote{position:absolute;bottom:calc(100% + 8px);z-index:3;width:max-content;max-width:320px;padding:6px 10px;border-radius:8px;background:var(--dsw-alias-surface-elevated,#2a2a2e);color:var(--dsw-alias-label-primary,#fff);font-size:12px;line-height:16px;box-shadow:0 4px 16px rgba(0,0,0,.3);white-space:normal}
8956
+ @keyframes codexVoicePulse{50%{opacity:.55}}
8957
+ @media (prefers-reduced-motion:reduce){.codexVoiceCall{animation:none!important}}
8958
+
8959
+ @keyframes codexVoiceStageIn{from{opacity:0;margin-top:8px}to{opacity:1;margin-top:0}}
8960
+ @media (prefers-reduced-motion:reduce){.codexVoiceOrb,.codexVoiceDot,.codexVoiceStage,.codexVoiceLines p{animation:none!important;transition:none!important}}
8961
+ .codexVoiceStage{position:fixed;z-index:60;display:flex;flex-direction:column;align-items:center;gap:6px;width:min(560px,92vw);pointer-events:none;animation:codexVoiceStageIn .28s cubic-bezier(.33,1,.68,1)}
8962
+ .codexVoiceStage[data-side=above]{transform:translate(-50%,calc(-100% - 16px))}
8963
+ .codexVoiceStage[data-side=below]{transform:translate(-50%,22px);flex-direction:column-reverse}
8964
+ .codexVoiceOrbBox{position:relative;width:120px;height:120px;flex:none;margin:-14px 0}
8965
+ .codexVoiceOrb{position:absolute;inset:0;transition:opacity .5s ease}
8966
+ .codexVoiceOrb[data-ready=false]{opacity:0}
8967
+ .codexVoiceOrb canvas{display:block;width:100%;height:100%}
8968
+ .codexVoiceDot{position:absolute;left:35px;top:35px;width:50px;height:50px;border-radius:50%;background:var(--dsw-alias-label-primary,#fff);animation:codexVoicePulse 1.1s ease-in-out infinite;transition:opacity .35s ease,transform .5s cubic-bezier(.33,1,.68,1)}
8969
+ .codexVoiceDot[data-gone=true]{opacity:0;transform:scale(1.8);animation:none}
8970
+ .codexVoiceLines{display:flex;flex-direction:column;align-items:center;gap:2px;max-width:100%;min-height:0;text-align:center}
8971
+ .codexVoiceLines p{margin:0;max-width:100%;font-size:13px;line-height:19px;color:var(--dsw-alias-label-primary);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;animation:codexVoiceStageIn .28s cubic-bezier(.33,1,.68,1)}
8972
+ .codexVoiceLines p[data-role=user]{color:var(--dsw-alias-label-secondary)}
8973
+ .codexVoiceLines p[data-old]{opacity:.45}
8974
+ .codexVoiceStatus{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
8975
+ .codexVoiceTools{display:inline-flex;align-items:center;gap:2px}
8976
+ [data-voice-live]>[data-slot="conversation.input.activity"]{display:none!important}
8977
+ .codexVoiceTool{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer}
8978
+ .codexVoiceTool:hover{background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary)}
8979
+ .codexVoiceTool[aria-pressed=true]{color:var(--dsw-alias-label-tertiary)}
8980
+
8981
+ /* Every fold-out in the settings reads as pressable: a full-width row, a chevron on the right that turns when it opens, a hover state. */
8982
+ .codexSubscriptionHistory>summary,.codexSubscriptionSearchOptions>summary,.codexSubscriptionRuntime summary,.codexSubscriptionDiagnostics details>summary,.codexImageDetails summary{display:flex;align-items:center;gap:8px;width:auto;box-sizing:border-box;min-height:32px;margin:0 -10px;padding:4px 10px;border-radius:8px;list-style:none;cursor:pointer;user-select:none;font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary);transition:background .12s}
8983
+ .codexSubscriptionHistory>summary::-webkit-details-marker,.codexSubscriptionSearchOptions>summary::-webkit-details-marker,.codexSubscriptionRuntime summary::-webkit-details-marker,.codexSubscriptionDiagnostics details>summary::-webkit-details-marker,.codexImageDetails summary::-webkit-details-marker{display:none}
8984
+ .codexSubscriptionHistory>summary::after,.codexSubscriptionSearchOptions>summary::after,.codexSubscriptionRuntime summary::after,.codexSubscriptionDiagnostics details>summary::after,.codexImageDetails summary::after{content:"";flex:none;margin-left:auto;width:7px;height:7px;border:solid var(--dsw-alias-label-tertiary);border-width:0 1.6px 1.6px 0;transform:translateY(-2px) rotate(45deg);transition:transform .15s,border-color .12s}
8985
+ .codexSubscriptionHistory[open]>summary::after,.codexSubscriptionSearchOptions[open]>summary::after,.codexSubscriptionRuntime details[open]>summary::after,.codexSubscriptionDiagnostics details[open]>summary::after,.codexImageDetails[open]>summary::after{transform:translateY(2px) rotate(-135deg)}
8986
+ .codexSubscriptionHistory>summary:hover,.codexSubscriptionSearchOptions>summary:hover,.codexSubscriptionRuntime summary:hover,.codexSubscriptionDiagnostics details>summary:hover,.codexImageDetails summary:hover{background:var(--dsw-alias-interactive-bg-hover)}
8987
+ .codexSubscriptionHistory>summary:hover::after,.codexSubscriptionSearchOptions>summary:hover::after,.codexSubscriptionRuntime summary:hover::after,.codexSubscriptionDiagnostics details>summary:hover::after,.codexImageDetails summary:hover::after{border-color:var(--dsw-alias-label-primary)}
8988
+ .codexSubscriptionHistory>summary:focus-visible,.codexSubscriptionSearchOptions>summary:focus-visible,.codexSubscriptionRuntime summary:focus-visible,.codexSubscriptionDiagnostics details>summary:focus-visible,.codexImageDetails summary:focus-visible{outline:2px solid var(--dsw-alias-border-l3);outline-offset:0}
8989
+ .codexSubscriptionSearchOptions>summary>span{float:none;margin-left:auto;font-weight:400}
8990
+ .codexSubscriptionSearchOptions>summary::after{margin-left:6px}
8991
+ .codexSubscriptionRuntime summary{font-size:12px}
8992
+ .codexSubscriptionHintToggle{margin:2px 0 0 -6px;padding:1px 6px;border-radius:6px;font-size:12px;font-weight:500;color:var(--dsw-alias-label-primary);transition:background .12s}
8993
+ .codexSubscriptionHintToggle::after{width:6px;height:6px}
8994
+ .codexSubscriptionHintToggle:hover{background:var(--dsw-alias-interactive-bg-hover)}
7258
8995
  `;
7259
8996
  //#endregion
7260
8997
  //#region src/image-edit-reference.js
@@ -7263,10 +9000,10 @@ window.__ModuleLoader__.load({
7263
9000
  const PIN_OUTER_STROKE = "#111827";
7264
9001
  const PIN_INNER_STROKE = "#ffffff";
7265
9002
  const finiteDimension = (value) => Number.isSafeInteger(value) && value > 0;
7266
- const clamp$2 = (value, min, max) => Math.min(max, Math.max(min, value));
9003
+ const clamp$3 = (value, min, max) => Math.min(max, Math.max(min, value));
7267
9004
  const clampCenter = (value, size, edge) => {
7268
9005
  const margin = Math.min(edge, size / 2);
7269
- return clamp$2(value, margin, size - margin);
9006
+ return clamp$3(value, margin, size - margin);
7270
9007
  };
7271
9008
  function getBitmapFactory(options) {
7272
9009
  const factory = options?.createImageBitmap ?? options?.bitmapFactory ?? globalThis.createImageBitmap;
@@ -7403,7 +9140,7 @@ window.__ModuleLoader__.load({
7403
9140
  `;
7404
9141
  //#endregion
7405
9142
  //#region src/subscription-image-transform.js
7406
- const clamp$1 = (value, min, max) => Math.min(max, Math.max(min, value));
9143
+ const clamp$2 = (value, min, max) => Math.min(max, Math.max(min, value));
7407
9144
  const fitted = () => ({
7408
9145
  zoom: 1,
7409
9146
  x: 0,
@@ -7445,15 +9182,15 @@ window.__ModuleLoader__.load({
7445
9182
  const limitX = Math.max(0, (surface.offsetWidth * zoom - stage.clientWidth) / 2);
7446
9183
  const limitY = Math.max(0, (surface.offsetHeight * zoom - stage.clientHeight) / 2);
7447
9184
  return {
7448
- x: clamp$1(x, -limitX, limitX),
7449
- y: clamp$1(y, -limitY, limitY)
9185
+ x: clamp$2(x, -limitX, limitX),
9186
+ y: clamp$2(y, -limitY, limitY)
7450
9187
  };
7451
9188
  }, []);
7452
9189
  const setZoomAt = (0, react.useCallback)((zoom, clientX, clientY) => {
7453
9190
  const stage = stageRef.current;
7454
9191
  if (!stage) return;
7455
9192
  setTransform((current) => {
7456
- const next = clamp$1(zoom, .5, Math.max(8, actualScale()));
9193
+ const next = clamp$2(zoom, .5, Math.max(8, actualScale()));
7457
9194
  const box = stage.getBoundingClientRect();
7458
9195
  const px = clientX - box.left - box.width / 2, py = clientY - box.top - box.height / 2;
7459
9196
  const ratio = next / current.zoom;
@@ -7594,7 +9331,7 @@ window.__ModuleLoader__.load({
7594
9331
  }) : null;
7595
9332
  };
7596
9333
  const fill$1 = (value, variables) => Object.entries(variables).reduce((text, [key, replacement]) => text.replaceAll(`{${key}}`, String(replacement)), value);
7597
- const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
9334
+ const clamp$1 = (value, min, max) => Math.min(max, Math.max(min, value));
7598
9335
  const bytesLabel = (bytes) => bytes === void 0 ? void 0 : bytes < 1024 * 1024 ? `${Math.max(.1, bytes / 1024).toLocaleString(void 0, { maximumFractionDigits: 1 })} KB` : `${(bytes / 1024 / 1024).toLocaleString(void 0, { maximumFractionDigits: 1 })} MB`;
7599
9336
  const downloadName = (name) => {
7600
9337
  const cleaned = String(name || "image.png").replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "-").replace(/[. ]+$/u, "").trim();
@@ -7879,7 +9616,7 @@ window.__ModuleLoader__.load({
7879
9616
  }
7880
9617
  if (event.key === "[" || event.key === "]") {
7881
9618
  event.preventDefault();
7882
- setBrush((value) => Math.round(clamp(value + (event.key === "]" ? .01 : -.01), .01, .15) * 100) / 100);
9619
+ setBrush((value) => Math.round(clamp$1(value + (event.key === "]" ? .01 : -.01), .01, .15) * 100) / 100);
7883
9620
  return;
7884
9621
  }
7885
9622
  if (event.key === "ArrowLeft" || event.key === "ArrowRight") return;
@@ -7965,8 +9702,8 @@ window.__ModuleLoader__.load({
7965
9702
  const bounds = maskRef.current?.getBoundingClientRect();
7966
9703
  if (bounds === void 0) return void 0;
7967
9704
  return {
7968
- x: clamp((event.clientX - bounds.left) / bounds.width, 0, 1),
7969
- y: clamp((event.clientY - bounds.top) / bounds.height, 0, 1)
9705
+ x: clamp$1((event.clientX - bounds.left) / bounds.width, 0, 1),
9706
+ y: clamp$1((event.clientY - bounds.top) / bounds.height, 0, 1)
7970
9707
  };
7971
9708
  };
7972
9709
  const maskHandlers = {
@@ -8046,8 +9783,8 @@ window.__ModuleLoader__.load({
8046
9783
  if (bounds === void 0) return;
8047
9784
  const annotation = {
8048
9785
  id: crypto.randomUUID(),
8049
- x: clamp((event.clientX - bounds.left) / bounds.width, 0, 1),
8050
- y: clamp((event.clientY - bounds.top) / bounds.height, 0, 1),
9786
+ x: clamp$1((event.clientX - bounds.left) / bounds.width, 0, 1),
9787
+ y: clamp$1((event.clientY - bounds.top) / bounds.height, 0, 1),
8051
9788
  note: ""
8052
9789
  };
8053
9790
  setAnnotations((current) => [...current, annotation]);
@@ -8613,6 +10350,51 @@ window.__ModuleLoader__.load({
8613
10350
  const OUTPUT_VERBOSITY_MEDIUM = "medium";
8614
10351
  const OUTPUT_VERBOSITY_HIGH = "high";
8615
10352
  const DEFAULT_OUTPUT_VERBOSITY = OUTPUT_VERBOSITY_DEFAULT;
10353
+ const VOICE_CALL_FIELD = "voiceCall";
10354
+ const VOICE_VOICE_FIELD = "voiceVoice";
10355
+ const VOICE_VOICES = Object.freeze([
10356
+ "cove",
10357
+ "juniper",
10358
+ "maple",
10359
+ "spruce",
10360
+ "ember",
10361
+ "vale",
10362
+ "breeze",
10363
+ "arbor",
10364
+ "sol",
10365
+ "aube",
10366
+ "bubbie",
10367
+ "haetsal",
10368
+ "hanul",
10369
+ "himari",
10370
+ "leher",
10371
+ "miko",
10372
+ "neer",
10373
+ "porto",
10374
+ "rindo",
10375
+ "rio",
10376
+ "rivage",
10377
+ "selva",
10378
+ "sonna",
10379
+ "tinta",
10380
+ "viola"
10381
+ ]);
10382
+ const VOICE_LANGUAGE_FIELD = "voiceLanguage";
10383
+ const VOICE_LANGUAGES = Object.freeze([
10384
+ "auto",
10385
+ "zh",
10386
+ "en",
10387
+ "ja",
10388
+ "ko",
10389
+ "es",
10390
+ "fr",
10391
+ "de",
10392
+ "pt",
10393
+ "ru"
10394
+ ]);
10395
+ const normalizeVoiceCall = (value) => value === "off" ? "off" : "on";
10396
+ const normalizeVoiceVoice = (value) => VOICE_VOICES.includes(value) ? value : "cove";
10397
+ const normalizeVoiceLanguage = (value) => VOICE_LANGUAGES.includes(value) ? value : "auto";
8616
10398
  const REASONING_SUMMARY_FIELD = "reasoningSummary";
8617
10399
  const REASONING_SUMMARIES = Object.freeze([
8618
10400
  "auto",
@@ -8769,6 +10551,7 @@ window.__ModuleLoader__.load({
8769
10551
  connectionMode: value?.connectionMode === "websocket" ? "websocket" : "sse",
8770
10552
  reviewModel: value?.reviewModel === "official" ? "official" : "session",
8771
10553
  remoteControl: value?.remoteControl === "on" ? "on" : "off",
10554
+ otherModels: value?.otherModels === "off" ? "off" : "on",
8772
10555
  compactionMode: value?.compactionMode === "cloud" ? "cloud" : "dsh",
8773
10556
  subagentBackend: value?.subagentBackend === "codex" ? "codex" : "dsh",
8774
10557
  subagentBackendAvailable,
@@ -8779,6 +10562,9 @@ window.__ModuleLoader__.load({
8779
10562
  outputVerbosity: normalizeOutputVerbosity(value?.[OUTPUT_VERBOSITY_FIELD]),
8780
10563
  inputImageDetail: normalizeInputImageDetail(value?.[INPUT_IMAGE_DETAIL_FIELD]),
8781
10564
  reasoningSummary: normalizeReasoningSummary(value?.[REASONING_SUMMARY_FIELD]),
10565
+ voiceCall: normalizeVoiceCall(value?.[VOICE_CALL_FIELD]),
10566
+ voiceVoice: normalizeVoiceVoice(value?.[VOICE_VOICE_FIELD]),
10567
+ voiceLanguage: normalizeVoiceLanguage(value?.[VOICE_LANGUAGE_FIELD]),
8782
10568
  retryPolicy: normalizeRetryPolicy(value?.[RETRY_POLICY_FIELD]),
8783
10569
  connectors: normalizeConnectorMode(value?.[CONNECTORS_FIELD]),
8784
10570
  streamIdleTimeoutMinutes: normalizeStreamIdleTimeoutMinutes(value?.[STREAM_IDLE_TIMEOUT_MINUTES_FIELD]),
@@ -8829,6 +10615,8 @@ window.__ModuleLoader__.load({
8829
10615
  connectionMode: value?.connectionMode === "websocket" ? "websocket" : "sse",
8830
10616
  reviewModel: value?.reviewModel === "official" ? "official" : "session",
8831
10617
  remoteControl: value?.remoteControl === "on" ? "on" : "off",
10618
+ otherModels: value?.otherModels === "off" ? "off" : "on",
10619
+ otherModels: value?.otherModels === "off" ? "off" : "on",
8832
10620
  compactionMode: value?.compactionMode === "cloud" ? "cloud" : "dsh",
8833
10621
  subagentBackend: value?.subagentBackend === "codex" ? "codex" : "dsh",
8834
10622
  ...readCapabilitySettings(value),
@@ -8838,6 +10626,9 @@ window.__ModuleLoader__.load({
8838
10626
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(value?.[OUTPUT_VERBOSITY_FIELD]),
8839
10627
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(value?.[INPUT_IMAGE_DETAIL_FIELD]),
8840
10628
  [REASONING_SUMMARY_FIELD]: normalizeReasoningSummary(value?.[REASONING_SUMMARY_FIELD]),
10629
+ [VOICE_CALL_FIELD]: normalizeVoiceCall(value?.[VOICE_CALL_FIELD]),
10630
+ [VOICE_VOICE_FIELD]: normalizeVoiceVoice(value?.[VOICE_VOICE_FIELD]),
10631
+ [VOICE_LANGUAGE_FIELD]: normalizeVoiceLanguage(value?.[VOICE_LANGUAGE_FIELD]),
8841
10632
  [RETRY_POLICY_FIELD]: normalizeRetryPolicy(value?.[RETRY_POLICY_FIELD]),
8842
10633
  [CONNECTORS_FIELD]: normalizeConnectorMode(value?.[CONNECTORS_FIELD]),
8843
10634
  [STREAM_IDLE_TIMEOUT_MINUTES_FIELD]: normalizeStreamIdleTimeoutMinutes(value?.[STREAM_IDLE_TIMEOUT_MINUTES_FIELD]),
@@ -9325,7 +11116,7 @@ window.__ModuleLoader__.load({
9325
11116
  }
9326
11117
  //#endregion
9327
11118
  //#region src/version.js
9328
- const PACKAGE_VERSION = "3.0.0";
11119
+ const PACKAGE_VERSION = "3.1.0";
9329
11120
  //#endregion
9330
11121
  //#region src/client-recovery.js
9331
11122
  async function recoveryCall(rpc, endpoint, payload = {}, timeoutMs = 1e4) {
@@ -9601,7 +11392,7 @@ window.__ModuleLoader__.load({
9601
11392
  left: 0,
9602
11393
  top: 0
9603
11394
  };
9604
- function CodexModelSelect({ locked, available, directory, load, select, preference, t }) {
11395
+ function CodexModelSelect({ locked, available, directory, load, select, preference, t, renderSlot }) {
9605
11396
  const state = (0, react.useSyncExternalStore)(directory.subscribe, directory.getSnapshot);
9606
11397
  const preferenceSnapshot = usePreferenceSnapshot(preference);
9607
11398
  const [open, setOpen] = (0, react.useState)(false);
@@ -9644,6 +11435,26 @@ window.__ModuleLoader__.load({
9644
11435
  ...effort.description === void 0 ? {} : { description: effort.description }
9645
11436
  }))], [reasoning, t]);
9646
11437
  const modelLabel = currentChoice?.model.name ?? t("selectModel");
11438
+ const labelOf = (group, model, placement, selected) => {
11439
+ if (typeof renderSlot !== "function") return model.name;
11440
+ try {
11441
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
11442
+ "data-provider-id": group.id,
11443
+ "data-model-id": model.id,
11444
+ children: renderSlot("conversation.input.model.label", {
11445
+ provider: {
11446
+ id: group.id,
11447
+ name: group.name
11448
+ },
11449
+ model,
11450
+ placement,
11451
+ selected
11452
+ }, { fallback: model.name })
11453
+ });
11454
+ } catch {
11455
+ return model.name;
11456
+ }
11457
+ };
9647
11458
  const searchable = visibleGroups.reduce((total, group) => total + group.models.length, 0) > 4;
9648
11459
  const needle = searchable ? query.trim().toLocaleLowerCase() : "";
9649
11460
  const shownGroups = needle === "" ? visibleGroups : visibleGroups.map((group) => ({
@@ -9837,7 +11648,7 @@ window.__ModuleLoader__.load({
9837
11648
  }, key);
9838
11649
  let content = null;
9839
11650
  if (pane === "root") content = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
9840
- cell("model", t("modelLabel"), modelLabel),
11651
+ cell("model", t("modelLabel"), currentChoice === void 0 ? modelLabel : labelOf(currentChoice.group, currentChoice.model, "menu", true)),
9841
11652
  reasoning === void 0 ? null : cell("effort", t("effortLabel"), effortLabel),
9842
11653
  (speedSupported || ultrafastSupported) && cell("speed", t("speedTitle"), t(speedKey)),
9843
11654
  verbositySupported && cell("verbosity", t("verbosityTitle"), verbosityLabel)
@@ -9885,7 +11696,7 @@ window.__ModuleLoader__.load({
9885
11696
  children: t("modelsHidden")
9886
11697
  }) : null, entry.models.map((model) => option({
9887
11698
  key: model.id,
9888
- label: model.name,
11699
+ label: labelOf(entry, model, "option", state.current?.provider === entry.id && state.current.model === model.id),
9889
11700
  selected: state.current?.provider === entry.id && state.current.model === model.id,
9890
11701
  disabled: busy,
9891
11702
  onClick: () => chooseModel({
@@ -9992,7 +11803,7 @@ window.__ModuleLoader__.load({
9992
11803
  }),
9993
11804
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
9994
11805
  className: "codexModelSelectLabel",
9995
- children: modelLabel
11806
+ children: currentChoice === void 0 ? modelLabel : labelOf(currentChoice.group, currentChoice.model, "trigger", true)
9996
11807
  }),
9997
11808
  effortLabel === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
9998
11809
  className: "codexModelSelectEffort",
@@ -10003,49 +11814,1228 @@ window.__ModuleLoader__.load({
10003
11814
  }), menu]
10004
11815
  });
10005
11816
  }
10006
- //#endregion
10007
- //#region src/client-hint.jsx
10008
- /** A setting's explanation: shows up to two lines; a "More" link appears only when the text is actually cut off. */
11817
+ /** A setting's explanation: short text is shown whole; only text that would save several lines when folded gets a "More" link. */
10009
11818
  function Hint({ children, t, as: Tag = "span" }) {
10010
11819
  const [open, setOpen] = (0, react.useState)(false);
10011
- const [clipped, setClipped] = (0, react.useState)(false);
11820
+ const [lines, setLines] = (0, react.useState)(0);
10012
11821
  const text = (0, react.useRef)(null);
10013
11822
  const id = (0, react.useId)();
10014
11823
  const foldable = typeof children === "string";
10015
11824
  (0, react.useLayoutEffect)(() => {
10016
11825
  const node = text.current;
10017
- if (!foldable || node === null || open) return;
10018
- const measure = () => setClipped(node.scrollHeight > node.clientHeight + 1);
11826
+ if (!foldable || node === null) return;
11827
+ const measure = () => setLines(Math.round(node.scrollHeight / (Number.parseFloat(getComputedStyle(node).lineHeight) || 17)));
10019
11828
  measure();
10020
11829
  if (typeof ResizeObserver !== "function") return;
10021
11830
  const observer = new ResizeObserver(measure);
10022
11831
  observer.observe(node);
10023
11832
  return () => observer.disconnect();
10024
- }, [
10025
- children,
10026
- foldable,
10027
- open
10028
- ]);
11833
+ }, [children, foldable]);
10029
11834
  if (!foldable) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Tag, {
10030
11835
  className: "codexSubscriptionPreferenceHint",
10031
11836
  children
10032
11837
  });
10033
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Tag, {
10034
- className: "codexSubscriptionPreferenceHint codexSubscriptionHintFold",
10035
- "data-open": open || void 0,
10036
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
10037
- id,
10038
- ref: text,
10039
- className: "codexSubscriptionHintText",
10040
- children
10041
- }), clipped || open ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
10042
- type: "button",
10043
- className: "codexSubscriptionHintToggle",
10044
- "aria-expanded": open,
10045
- "aria-controls": id,
10046
- onClick: () => setOpen((value) => !value),
10047
- children: t(open ? "hintLess" : "hintMore")
10048
- }) : null]
11838
+ const folds = lines >= 6;
11839
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Tag, {
11840
+ className: "codexSubscriptionPreferenceHint codexSubscriptionHintFold",
11841
+ "data-fold": folds && !open ? "true" : void 0,
11842
+ "data-open": open || void 0,
11843
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
11844
+ id,
11845
+ ref: text,
11846
+ className: "codexSubscriptionHintText",
11847
+ children
11848
+ }), folds ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
11849
+ type: "button",
11850
+ className: "codexSubscriptionHintToggle",
11851
+ "aria-expanded": open,
11852
+ "aria-controls": id,
11853
+ onClick: () => setOpen((value) => !value),
11854
+ children: t(open ? "hintLess" : "hintMore")
11855
+ }) : null]
11856
+ });
11857
+ }
11858
+ //#endregion
11859
+ //#region src/voice-call.js
11860
+ const ICE_WAIT_MS = 3e3;
11861
+ const waitForCandidates = (connection) => new Promise((resolve) => {
11862
+ if (connection.iceGatheringState === "complete") {
11863
+ resolve();
11864
+ return;
11865
+ }
11866
+ const done = () => {
11867
+ clearTimeout(timer);
11868
+ connection.removeEventListener("icegatheringstatechange", check);
11869
+ resolve();
11870
+ };
11871
+ const check = () => {
11872
+ if (connection.iceGatheringState === "complete") done();
11873
+ };
11874
+ const timer = setTimeout(done, ICE_WAIT_MS);
11875
+ connection.addEventListener("icegatheringstatechange", check);
11876
+ });
11877
+ /** Two short soft tones: rising when a call starts, falling when it ends. */
11878
+ const chime = (context, frequencies) => {
11879
+ try {
11880
+ const now = context.currentTime;
11881
+ frequencies.forEach((frequency, index) => {
11882
+ const tone = context.createOscillator();
11883
+ const gain = context.createGain();
11884
+ const start = now + index * .11;
11885
+ tone.type = "sine";
11886
+ tone.frequency.value = frequency;
11887
+ gain.gain.setValueAtTime(0, start);
11888
+ gain.gain.linearRampToValueAtTime(.07, start + .02);
11889
+ gain.gain.exponentialRampToValueAtTime(1e-4, start + .16);
11890
+ tone.connect(gain).connect(context.destination);
11891
+ tone.start(start);
11892
+ tone.stop(start + .18);
11893
+ });
11894
+ } catch {}
11895
+ };
11896
+ /** Loudness of an analyser as 0..1 (the root mean square of the waveform, lifted so quiet speech still moves the orb). */
11897
+ const loudness = (analyser, buffer) => {
11898
+ if (!analyser) return 0;
11899
+ analyser.getByteTimeDomainData(buffer);
11900
+ let sum = 0;
11901
+ for (const value of buffer) {
11902
+ const centred = (value - 128) / 128;
11903
+ sum += centred * centred;
11904
+ }
11905
+ return Math.min(1, Math.sqrt(sum / buffer.length) * 3.2);
11906
+ };
11907
+ /**
11908
+ * A voice call from this window: the microphone and the model's voice travel over WebRTC straight to OpenAI; the
11909
+ * plugin's host turns the offer into a call, joins it, and runs what is asked as turns of this conversation.
11910
+ * Resolves with a handle once the call is connected; rejects with the reason when it could not start.
11911
+ */
11912
+ async function openVoiceCall({ rpc, sessionId, onEnd }) {
11913
+ if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia || typeof RTCPeerConnection !== "function") throw new Error("unsupported");
11914
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: {
11915
+ echoCancellation: true,
11916
+ noiseSuppression: true,
11917
+ autoGainControl: true
11918
+ } });
11919
+ const connection = new RTCPeerConnection();
11920
+ const sound = new Audio();
11921
+ sound.autoplay = true;
11922
+ const AudioContextClass = window.AudioContext ?? window.webkitAudioContext;
11923
+ const context = AudioContextClass ? new AudioContextClass() : void 0;
11924
+ const analysers = {
11925
+ mic: void 0,
11926
+ assistant: void 0
11927
+ };
11928
+ const watch = (name, source) => {
11929
+ if (!context) return;
11930
+ try {
11931
+ const analyser = context.createAnalyser();
11932
+ analyser.fftSize = 512;
11933
+ context.createMediaStreamSource(source).connect(analyser);
11934
+ analysers[name] = analyser;
11935
+ } catch {}
11936
+ };
11937
+ watch("mic", stream);
11938
+ connection.ontrack = (event) => {
11939
+ sound.srcObject = event.streams[0];
11940
+ watch("assistant", event.streams[0]);
11941
+ };
11942
+ for (const track of stream.getTracks()) connection.addTrack(track, stream);
11943
+ connection.createDataChannel("oai-events");
11944
+ let ended = false;
11945
+ const end = async () => {
11946
+ if (ended) return;
11947
+ ended = true;
11948
+ if (context) chime(context, [740, 520]);
11949
+ for (const track of stream.getTracks()) track.stop();
11950
+ sound.srcObject = null;
11951
+ try {
11952
+ connection.close();
11953
+ } catch {}
11954
+ try {
11955
+ await rpc.call(CHANNEL, "voice/stop", { sessionId });
11956
+ } catch {}
11957
+ setTimeout(() => {
11958
+ context?.close().catch(() => {});
11959
+ }, 600);
11960
+ onEnd?.();
11961
+ };
11962
+ connection.addEventListener("connectionstatechange", () => {
11963
+ if ([
11964
+ "failed",
11965
+ "disconnected",
11966
+ "closed"
11967
+ ].includes(connection.connectionState)) end();
11968
+ });
11969
+ try {
11970
+ await context?.resume();
11971
+ await connection.setLocalDescription(await connection.createOffer());
11972
+ await waitForCandidates(connection);
11973
+ const result = await rpc.call(CHANNEL, "voice/start", {
11974
+ sessionId,
11975
+ sdp: connection.localDescription.sdp
11976
+ });
11977
+ if (!result.ok) throw new Error(result.error?.message ?? "start failed");
11978
+ await connection.setRemoteDescription({
11979
+ type: "answer",
11980
+ sdp: result.value.answer
11981
+ });
11982
+ } catch (error) {
11983
+ ended = true;
11984
+ for (const track of stream.getTracks()) track.stop();
11985
+ try {
11986
+ connection.close();
11987
+ } catch {}
11988
+ context?.close().catch(() => {});
11989
+ throw error;
11990
+ }
11991
+ if (context) chime(context, [520, 740]);
11992
+ const buffers = {
11993
+ mic: /* @__PURE__ */ new Uint8Array(512),
11994
+ assistant: /* @__PURE__ */ new Uint8Array(512)
11995
+ };
11996
+ let muted = false;
11997
+ return {
11998
+ stop: end,
11999
+ isMuted: () => muted,
12000
+ setMuted: (value) => {
12001
+ muted = value;
12002
+ for (const track of stream.getAudioTracks()) track.enabled = !value;
12003
+ },
12004
+ isOutputMuted: () => sound.muted,
12005
+ setOutputMuted: (value) => {
12006
+ sound.muted = value;
12007
+ },
12008
+ /** How loud the person (mic) and the model (voice) are right now, 0..1 each. */
12009
+ levels: () => ({
12010
+ mic: muted ? 0 : loudness(analysers.mic, buffers.mic),
12011
+ assistant: loudness(analysers.assistant, buffers.assistant)
12012
+ })
12013
+ };
12014
+ }
12015
+ //#endregion
12016
+ //#region src/voice-orb.js
12017
+ const VERTEX = "attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}";
12018
+ const FRAGMENT = `
12019
+ precision highp float;
12020
+ uniform vec2 uRes;
12021
+ uniform float uWaveFrame;
12022
+ uniform float uBaseFrame;
12023
+ uniform float uAmp;
12024
+ uniform float uFlowFrame;
12025
+ uniform float uEdge;
12026
+ uniform float uNoiseScale;
12027
+ uniform float uSurface;
12028
+ uniform float uMic;
12029
+ uniform float uUser;
12030
+ uniform float uFlat;
12031
+ uniform vec2 uOff0;
12032
+ uniform vec2 uOff1;
12033
+ uniform vec2 uOff2;
12034
+ uniform vec3 uAccent;
12035
+
12036
+ float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
12037
+ vec2 hash2(vec2 p){return vec2(hash(p),hash(p+vec2(19.19,73.73)));}
12038
+ float vnoise(vec2 p){
12039
+ vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);
12040
+ return mix(mix(hash(i),hash(i+vec2(1.,0.)),f.x),mix(hash(i+vec2(0.,1.)),hash(i+vec2(1.,1.)),f.x),f.y);
12041
+ }
12042
+ float fbm(vec2 p,float rough,float lac){
12043
+ float a=vnoise(p);
12044
+ float b=vnoise(p*lac+vec2(17.17,31.31));
12045
+ float c=vnoise(p*lac*lac+vec2(47.47,11.11));
12046
+ return (a+b*rough+c*rough*rough)/(1.+rough+rough*rough);
12047
+ }
12048
+ vec3 noise3(vec3 coord,float w,float scale,float rough,float lac,float unit){
12049
+ vec2 p=coord.xy*scale;
12050
+ float t=w*scale;
12051
+ vec2 d1=vec2(.17,.11),d2=vec2(-.13,.19),d3=vec2(.07,-.23);
12052
+ if(unit>.5){d1=normalize(d1);d2=normalize(d2);d3=normalize(d3);}
12053
+ return vec3(fbm(p+d1*t,rough,lac),fbm(p+vec2(41.41,17.17)+d2*t,rough,lac),fbm(p+vec2(23.23,59.59)+d3*t,rough,lac));
12054
+ }
12055
+
12056
+ // the painted-paper texture: soft pale ground, darker stains with ragged edges, a fine fibre. Reads like grey watercolour.
12057
+ float paint(vec2 uv){
12058
+ vec2 w=vec2(vnoise(uv*3.+vec2(4.2,1.7)),vnoise(uv*3.+vec2(9.1,6.3)))-.5;
12059
+ vec2 q=uv+w*.3;
12060
+ float body=vnoise(q*2.+vec2(3.1,8.3))*.5+vnoise(q*4.3+vec2(9.7,1.9))*.3+vnoise(q*9.+vec2(2.3,5.5))*.2;
12061
+ float stain=smoothstep(.5,.64,body);
12062
+ float wash=smoothstep(.28,.6,vnoise(q*2.6+vec2(14.2,4.4)));
12063
+ float mott=vnoise(q*vec2(18.,16.)+vec2(5.,5.))*.55+vnoise(q*vec2(42.,36.))*.45;
12064
+ float ragged=stain*(1.-stain)*4.;
12065
+ float v=.92-.2*wash-.5*stain+(mott-.5)*(.1+.2*ragged);
12066
+ return clamp(v,.16,1.);
12067
+ }
12068
+
12069
+ vec3 warp3(vec3 c,float frame){
12070
+ vec2 pt=c.xy*8.;
12071
+ vec2 cell=floor(pt),local=fract(pt);
12072
+ vec2 nearest=vec2(0.);
12073
+ float best=3.4e38;
12074
+ float phase=frame*6.2831853/240.;
12075
+ for(int y=-1;y<=1;y++){for(int x=-1;x<=1;x++){
12076
+ vec2 off=vec2(float(x),float(y));
12077
+ vec2 r=hash2(cell+off);
12078
+ vec2 pos=off+r*.7185189723968506+sin(vec2(phase)+r*6.2831853)*.04;
12079
+ vec2 d=pos-local;
12080
+ float dd=dot(d,d);
12081
+ if(dd<best){best=dd;nearest=pos;}
12082
+ }}
12083
+ vec3 vor=vec3((nearest+cell)/8.,c.z);
12084
+ return (c-vec3(.5))*.26+(vor-c)*.06;
12085
+ }
12086
+
12087
+ vec3 rotY(vec3 v,float a){float c=cos(a),s=sin(a);return vec3(c*v.x+s*v.z,v.y,-s*v.x+c*v.z);}
12088
+ float fac(vec3 v,float lift){vec3 r=rotY(v,.7853981852531433)+vec3(0.,lift,0.);return (r.x+r.y+r.z)/3.;}
12089
+ // 1 below a, easing to 0 at b
12090
+ float ramp(float f,float a,float b){float t=clamp((f-a)/max(b-a,1e-6),0.,1.);t=t*t*(3.-2.*t);return 1.-t;}
12091
+
12092
+ vec3 interior(vec3 gen){
12093
+ vec3 a=uAccent;
12094
+ vec3 soft=mix(((16.*a-12.)*a+4.)*a,sqrt(a),step(.25,a));
12095
+ vec3 cShadow=max(vec3(0.),a+.9465623-1.);
12096
+ vec3 cMidLow=a+(2.*.89882153-1.)*(soft-a);
12097
+ vec3 cMidHigh=vec3(1.);
12098
+ vec3 cHigh=1.-(1.-a)*(1.-.63704175);
12099
+
12100
+ vec3 m=gen+vec3(0.,-.14,0.);
12101
+ vec2 cen=gen.xy-.5;
12102
+ float rad=length(cen);
12103
+ m.xy+=(rad>1e-6?cen/rad:vec2(0.))*smoothstep(.015,.44,rad)*uEdge;
12104
+ vec3 wave=noise3(m,uWaveFrame/100.,1.,.4,2.,1.);
12105
+ vec3 m2=m+(wave-.5)*(.8*uAmp);
12106
+ vec3 grain=noise3(m2,uFlowFrame/10.,4000.,.5,2.,0.);
12107
+ vec3 g2=(grain-.5)*uNoiseScale*.06;
12108
+ vec3 base=m2*.8+g2;
12109
+ float blend=clamp(.5-.5*cos(uBaseFrame*6.2831853/120.),0.,1.);
12110
+ vec3 cw=warp3(m2,uBaseFrame);
12111
+
12112
+ // tone 3: highlight
12113
+ vec2 p0=base.xy+uOff0;
12114
+ vec2 f0=vec2(base.x,1.-base.y)+uOff0;
12115
+ float s0=mix(paint(p0)-.5,paint(f0)-.5,blend)*(.2-.06*cos((uBaseFrame-1.)*6.2831853/120.));
12116
+ vec3 v6=m2+vec3(s0,s0,0.)+cw;
12117
+ float rHigh=ramp(fac(v6,.56),.3431819975376129,.6200000047683716);
12118
+
12119
+ // tone 2: white
12120
+ vec3 b1=m2*.8+vec3(.04,.02,0.)+g2;
12121
+ vec3 b2=m2*.8+vec3(-.04,-.02,0.)+g2;
12122
+ float s1=mix(paint(b1.xy+uOff1)-.5,paint(vec2(b2.x,1.-b2.y)+uOff1)-.5,blend)*(.2-.06*cos((uBaseFrame-1.)*6.2831853/80.));
12123
+ vec3 v5=m2+vec3(s1,s1,0.)+cw;
12124
+ float rMidHigh=ramp(fac(v5,.26),.4113636016845703,.5586364269256592);
12125
+
12126
+ // tone 1: mid-low, with the left-to-right fade the original uses
12127
+ float gx=clamp(gen.y-.32,0.,1.);
12128
+ float gradient=gx*gx*(3.-2.*gx);
12129
+ vec3 c1=m2*.8+vec3(-.08,-.04,0.)+g2;
12130
+ vec3 c2=m2*.8+vec3(-.96,.06,0.)+g2;
12131
+ float t1=mix(paint(c1.xy+uOff2),1.,gradient)-.5;
12132
+ float t2=mix(paint(vec2(c2.x,1.-c2.y)+uOff2),1.,gradient)-.5;
12133
+ float s2=mix(t1,t2,blend)*(.14-.06*cos((uBaseFrame-1.)*6.2831853/100.));
12134
+ vec3 v9=m2+vec3(s2,s2,0.)+cw;
12135
+ float rMidLow=ramp(fac(v9,.12),.3522728383541107,.7400000095367432);
12136
+
12137
+ vec3 col=cShadow;
12138
+ col=mix(col,cMidLow,rMidLow);
12139
+ col=mix(col,cMidHigh,rMidHigh);
12140
+ col=mix(col,cHigh,rHigh);
12141
+ return col;
12142
+ }
12143
+
12144
+ void main(){
12145
+ if(uFlat>.5){gl_FragColor=vec4(interior(vec3(gl_FragCoord.xy/uRes,.5)),1.);return;}
12146
+ vec2 frame=(gl_FragCoord.xy/uRes)*2.-1.;
12147
+ float user=clamp(uUser,0.,1.);
12148
+ float voice=max(1.-user*.14+user*clamp(uMic,0.,1.)*.08,.75);
12149
+ float scale=voice*uSurface;
12150
+ vec2 sdf=frame/scale;
12151
+ float dist=length(sdf)-1.;
12152
+ float px=2./uRes.x/scale;
12153
+ float shape=1.-smoothstep(-px,px,dist+px*.5);
12154
+ if(shape<=0.){gl_FragColor=vec4(0.);return;}
12155
+ vec3 col=interior(vec3(sdf*.5+.5,.5));
12156
+ gl_FragColor=vec4(col*shape,shape);
12157
+ }`;
12158
+ const parseColor = (text) => {
12159
+ const match = /(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)/u.exec(String(text));
12160
+ return match ? [
12161
+ Number(match[1]) / 255,
12162
+ Number(match[2]) / 255,
12163
+ Number(match[3]) / 255
12164
+ ] : [
12165
+ .25,
12166
+ .46,
12167
+ .9
12168
+ ];
12169
+ };
12170
+ const clamp = (value, low = 0, high = 1) => Math.min(Math.max(value, low), high);
12171
+ const smooth = (low, high, value) => {
12172
+ const t = clamp((value - low) / (high - low));
12173
+ return t * t * (3 - 2 * t);
12174
+ };
12175
+ const ease = (current, target, dt, attack, release) => current + (target - current) * (1 - Math.exp(-dt / (target > current ? attack : release)));
12176
+ const spring = (value, velocity, target, dt, frequency, damping) => {
12177
+ const omega = 2 * Math.PI * frequency;
12178
+ const steps = Math.max(1, Math.ceil(dt * 120));
12179
+ const h = dt / steps;
12180
+ let v = value;
12181
+ let w = velocity;
12182
+ for (let i = 0; i < steps; i += 1) {
12183
+ w += ((target - v) * omega * omega - w * 2 * damping * omega) * h;
12184
+ v += w * h;
12185
+ }
12186
+ return {
12187
+ value: v,
12188
+ velocity: w
12189
+ };
12190
+ };
12191
+ const TUNE = {
12192
+ fps: 24,
12193
+ startFrame: 350,
12194
+ surface: .34,
12195
+ fit: 1.4,
12196
+ speakSpeedScale: .56,
12197
+ speakSpeedBase: 1.8,
12198
+ speakSlowEnergy: 4.6,
12199
+ speakAmp: 1.5,
12200
+ minWaveSpeed: .72,
12201
+ edgeDistance: .102,
12202
+ edgeFrequency: 7,
12203
+ edgeDamping: .36,
12204
+ listenNoise: 2.2,
12205
+ flowScale: .96,
12206
+ driftScale: .1,
12207
+ windScale: .3,
12208
+ windSpeed: .65
12209
+ };
12210
+ const WIND = [
12211
+ .72,
12212
+ 1,
12213
+ 1.28
12214
+ ];
12215
+ /** Returns a renderer for the canvas, or undefined when this browser cannot draw it. */
12216
+ function createOrb(canvas, accent, options = {}) {
12217
+ const gl = canvas.getContext("webgl", {
12218
+ alpha: true,
12219
+ premultipliedAlpha: true,
12220
+ antialias: false
12221
+ });
12222
+ if (!gl) return void 0;
12223
+ const compile = (type, source) => {
12224
+ const shader = gl.createShader(type);
12225
+ gl.shaderSource(shader, source);
12226
+ gl.compileShader(shader);
12227
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader) || "shader");
12228
+ return shader;
12229
+ };
12230
+ let program;
12231
+ try {
12232
+ program = gl.createProgram();
12233
+ gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));
12234
+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));
12235
+ gl.linkProgram(program);
12236
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error("link");
12237
+ } catch (error) {
12238
+ options.onError?.(error);
12239
+ return;
12240
+ }
12241
+ gl.useProgram(program);
12242
+ const buffer = gl.createBuffer();
12243
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
12244
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
12245
+ -1,
12246
+ -1,
12247
+ 1,
12248
+ -1,
12249
+ -1,
12250
+ 1,
12251
+ 1,
12252
+ 1
12253
+ ]), gl.STATIC_DRAW);
12254
+ const position = gl.getAttribLocation(program, "a");
12255
+ gl.enableVertexAttribArray(position);
12256
+ gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
12257
+ const at = (name) => gl.getUniformLocation(program, name);
12258
+ const u = {};
12259
+ for (const name of [
12260
+ "uRes",
12261
+ "uWaveFrame",
12262
+ "uBaseFrame",
12263
+ "uAmp",
12264
+ "uFlowFrame",
12265
+ "uEdge",
12266
+ "uNoiseScale",
12267
+ "uSurface",
12268
+ "uMic",
12269
+ "uUser",
12270
+ "uFlat",
12271
+ "uOff0",
12272
+ "uOff1",
12273
+ "uOff2",
12274
+ "uAccent"
12275
+ ]) u[name] = at(name);
12276
+ const color = parseColor(accent);
12277
+ const flat = options.flat ? Number(options.flat) : 0;
12278
+ const s = {
12279
+ last: void 0,
12280
+ base: TUNE.startFrame,
12281
+ wave: TUNE.startFrame,
12282
+ flow: TUNE.startFrame,
12283
+ listen: 1,
12284
+ speak: 0,
12285
+ think: 0,
12286
+ level: 0,
12287
+ motion: 0,
12288
+ prevOverall: 0,
12289
+ accent: 0,
12290
+ cumulative: [
12291
+ 0,
12292
+ 0,
12293
+ 0
12294
+ ],
12295
+ drive: 0,
12296
+ boost: 0,
12297
+ boostV: 0,
12298
+ amp: 1,
12299
+ edge: 0,
12300
+ edgeV: 0,
12301
+ flowBoost: 0,
12302
+ colour: [
12303
+ 0,
12304
+ 0,
12305
+ 0
12306
+ ],
12307
+ phase: [
12308
+ 0,
12309
+ 2.1,
12310
+ 4.2
12311
+ ],
12312
+ user: 0,
12313
+ userOn: false,
12314
+ userFrom: 0,
12315
+ userAt: 0
12316
+ };
12317
+ return {
12318
+ /** Draw one frame. `now` in seconds; `input` = { mic, assistant, working, reduce } with levels 0..1. */
12319
+ draw(now, input) {
12320
+ const dt = s.last === void 0 ? .016 : clamp(now - s.last, 0, .1);
12321
+ s.last = now;
12322
+ const assistant = clamp(input.assistant ?? 0);
12323
+ const mic = clamp((input.mic ?? 0) * 1.75);
12324
+ const speaking = assistant > .05;
12325
+ const thinking = !speaking && !!input.working;
12326
+ const pace = input.reduce ? .5 : 1;
12327
+ const target = speaking ? {
12328
+ listen: .2,
12329
+ speak: 1,
12330
+ think: 0
12331
+ } : thinking ? {
12332
+ listen: .65,
12333
+ speak: 0,
12334
+ think: 1
12335
+ } : {
12336
+ listen: 1,
12337
+ speak: 0,
12338
+ think: 0
12339
+ };
12340
+ const k = 1 - Math.exp(-dt / .28);
12341
+ s.listen += (target.listen - s.listen) * k;
12342
+ s.speak += (target.speak - s.speak) * k;
12343
+ s.think += (target.think - s.think) * k;
12344
+ const overall = speaking ? assistant : 0;
12345
+ s.motion += (overall - s.motion) * (1 - Math.exp(-dt / .2));
12346
+ s.accent = Math.max(overall - s.prevOverall, 0) * 3.6;
12347
+ s.prevOverall = overall;
12348
+ for (let i = 0; i < 3; i += 1) s.cumulative[i] += overall * (i === 0 ? .82 : i === 1 ? .76 : .68) * dt * 60 * 40 * (1 - Math.exp(-dt / 2));
12349
+ const energy = clamp(Math.max(...s.cumulative) / 12);
12350
+ const waveLevel = overall > .024 ? (1 - Math.exp(-overall * 4)) ** 1.15 : 0;
12351
+ s.drive = ease(s.drive, waveLevel, dt, .045, .14);
12352
+ const speedTarget = s.drive * TUNE.speakSpeedScale * (TUNE.speakSpeedBase + Math.max(s.motion, energy) * TUNE.speakSlowEnergy + s.accent * .5);
12353
+ const boost = spring(s.boost, s.boostV, speedTarget, dt, 6, .76);
12354
+ s.boost = boost.value;
12355
+ s.boostV = boost.velocity;
12356
+ const waveSpeed = Math.max(TUNE.minWaveSpeed, 1 + s.boost);
12357
+ s.amp = ease(s.amp, 1 - waveLevel * (1 - TUNE.speakAmp), dt, .1, .28);
12358
+ const userDrive = clamp(s.user) * clamp(input.mic ?? 0);
12359
+ const edge = spring(s.edge, s.edgeV, userDrive * TUNE.edgeDistance, dt, TUNE.edgeFrequency, TUNE.edgeDamping);
12360
+ s.edge = edge.value;
12361
+ s.edgeV = edge.velocity;
12362
+ const noiseScale = 1 + userDrive * (TUNE.listenNoise - 1);
12363
+ s.flowBoost = ease(s.flowBoost, Math.max(s.motion, energy) * TUNE.flowScale, dt, .055, .16);
12364
+ const talking = !speaking && !thinking && (s.userOn ? mic > .32 : mic >= .48);
12365
+ if (talking !== s.userOn) {
12366
+ s.userFrom = s.user;
12367
+ s.userOn = talking;
12368
+ s.userAt = now;
12369
+ }
12370
+ s.user = s.userFrom + ((s.userOn ? 1 : 0) - s.userFrom) * clamp((now - s.userAt) / .14);
12371
+ const offsets = [
12372
+ [0, 0],
12373
+ [0, 0],
12374
+ [0, 0]
12375
+ ];
12376
+ const audio = s.cumulative.map((value) => clamp(value / 12));
12377
+ for (let i = 0; i < 3; i += 1) s.colour[i] = ease(s.colour[i], audio[i] * (speaking ? 1 : 0) * 1, dt, .07, .22);
12378
+ if (speaking) for (let i = 0; i < 3; i += 1) s.phase[i] += dt * TUNE.windSpeed * WIND[i] * (1 + s.colour[i] * 1.5);
12379
+ const [r, g, b] = s.colour;
12380
+ const [p0, p1, p2] = s.phase;
12381
+ const d = TUNE.driftScale;
12382
+ const w = TUNE.windScale;
12383
+ offsets[0] = [r * d + Math.sin(p0) * r * w, -g * d * .55 + Math.cos(p0 * .82) * g * w * .65];
12384
+ offsets[1] = [-g * d * .75 + Math.cos(p1 * .91) * g * w * .8, b * d + Math.sin(p1) * b * w];
12385
+ offsets[2] = [b * d * 1.1 + Math.sin(p2 * 1.07) * b * w * 1.1, r * d * .7 + Math.cos(p2) * r * w * .75];
12386
+ s.base += dt * pace * TUNE.fps;
12387
+ s.wave += dt * pace * TUNE.fps * waveSpeed;
12388
+ s.flow += dt * pace * TUNE.fps * (1 + s.flowBoost);
12389
+ s.level = ease(s.level, speaking ? assistant : 0, dt, .09, .3);
12390
+ const out = smooth(.04, .46, s.level);
12391
+ const breath = Math.sin(now * Math.PI * .34) * .5 + .5;
12392
+ const state = Math.max(s.listen, s.think, s.speak);
12393
+ let size = TUNE.surface * (.88 + .06 * s.think) * (.82 + .18 * smooth(0, .9, state));
12394
+ size += out * TUNE.surface * .12;
12395
+ size += (1 - s.think) * (1 - out) * breath * TUNE.surface * .01;
12396
+ const surface = Math.min(TUNE.surface, size) * 2 * TUNE.fit;
12397
+ gl.viewport(0, 0, canvas.width, canvas.height);
12398
+ gl.clearColor(0, 0, 0, 0);
12399
+ gl.clear(gl.COLOR_BUFFER_BIT);
12400
+ gl.uniform2f(u.uRes, canvas.width, canvas.height);
12401
+ gl.uniform1f(u.uWaveFrame, s.wave);
12402
+ gl.uniform1f(u.uBaseFrame, s.base);
12403
+ gl.uniform1f(u.uAmp, s.amp);
12404
+ gl.uniform1f(u.uFlowFrame, s.flow);
12405
+ gl.uniform1f(u.uEdge, s.edge);
12406
+ gl.uniform1f(u.uNoiseScale, noiseScale);
12407
+ gl.uniform1f(u.uSurface, surface);
12408
+ gl.uniform1f(u.uMic, mic);
12409
+ gl.uniform1f(u.uUser, s.user);
12410
+ gl.uniform1f(u.uFlat, flat);
12411
+ gl.uniform2f(u.uOff0, offsets[0][0], offsets[0][1]);
12412
+ gl.uniform2f(u.uOff1, offsets[1][0], offsets[1][1]);
12413
+ gl.uniform2f(u.uOff2, offsets[2][0], offsets[2][1]);
12414
+ gl.uniform3f(u.uAccent, color[0], color[1], color[2]);
12415
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
12416
+ },
12417
+ dispose() {
12418
+ try {
12419
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
12420
+ } catch {}
12421
+ }
12422
+ };
12423
+ }
12424
+ //#endregion
12425
+ //#region src/client-voice-call.jsx
12426
+ const Bars = () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
12427
+ width: "20",
12428
+ height: "20",
12429
+ viewBox: "0 0 20 20",
12430
+ fill: "none",
12431
+ "aria-hidden": "true",
12432
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12433
+ d: "M4 8.5v3M7 5.5v9M10 3v14M13 6v8M16 8.5v3",
12434
+ stroke: "currentColor",
12435
+ strokeWidth: "2.2",
12436
+ strokeLinecap: "round"
12437
+ })
12438
+ });
12439
+ const Cross = () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
12440
+ width: "14",
12441
+ height: "14",
12442
+ viewBox: "0 0 14 14",
12443
+ fill: "none",
12444
+ "aria-hidden": "true",
12445
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12446
+ d: "M3 3l8 8M11 3l-8 8",
12447
+ stroke: "currentColor",
12448
+ strokeWidth: "2",
12449
+ strokeLinecap: "round"
12450
+ })
12451
+ });
12452
+ const Mic = ({ off }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
12453
+ width: "18",
12454
+ height: "18",
12455
+ viewBox: "0 0 18 18",
12456
+ fill: "none",
12457
+ "aria-hidden": "true",
12458
+ children: [
12459
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
12460
+ x: "6.2",
12461
+ y: "1.8",
12462
+ width: "5.6",
12463
+ height: "9",
12464
+ rx: "2.8",
12465
+ stroke: "currentColor",
12466
+ strokeWidth: "1.5"
12467
+ }),
12468
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12469
+ d: "M3.5 8.4a5.5 5.5 0 0 0 11 0M9 13.9v2.3",
12470
+ stroke: "currentColor",
12471
+ strokeWidth: "1.5",
12472
+ strokeLinecap: "round"
12473
+ }),
12474
+ off ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12475
+ d: "M2.8 15.2 15.2 2.8",
12476
+ stroke: "currentColor",
12477
+ strokeWidth: "1.7",
12478
+ strokeLinecap: "round"
12479
+ }) : null
12480
+ ]
12481
+ });
12482
+ const Speaker = ({ off }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
12483
+ width: "18",
12484
+ height: "18",
12485
+ viewBox: "0 0 18 18",
12486
+ fill: "none",
12487
+ "aria-hidden": "true",
12488
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12489
+ d: "M3 7h2.6L9.5 3.8v10.4L5.6 11H3z",
12490
+ stroke: "currentColor",
12491
+ strokeWidth: "1.5",
12492
+ strokeLinejoin: "round"
12493
+ }), off ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12494
+ d: "M12.6 6.6l3.2 4.8M15.8 6.6l-3.2 4.8",
12495
+ stroke: "currentColor",
12496
+ strokeWidth: "1.5",
12497
+ strokeLinecap: "round"
12498
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
12499
+ d: "M12.3 6.5a3.6 3.6 0 0 1 0 5M14.4 4.6a6.4 6.4 0 0 1 0 8.8",
12500
+ stroke: "currentColor",
12501
+ strokeWidth: "1.5",
12502
+ strokeLinecap: "round"
12503
+ })]
12504
+ });
12505
+ /**
12506
+ * What a call looks like while it runs, drawn like Codex's own voice chat: above a composer that sits at the bottom of the
12507
+ * conversation (below it on the empty start page) there is a small stage with the last spoken lines, what DSH is doing
12508
+ * and the orb, which swells with the person's voice and with the model's. While the call connects, the orb is a pulsing dot.
12509
+ */
12510
+ function VoiceStage({ call, connecting, rpc, sessionId, anchor, accent, t }) {
12511
+ const orb = (0, react.useRef)(null);
12512
+ const canvas = (0, react.useRef)(null);
12513
+ const working = (0, react.useRef)(false);
12514
+ const closing = (0, react.useRef)(false);
12515
+ const frame = (0, react.useRef)(null);
12516
+ const [status, setStatus] = (0, react.useState)({
12517
+ working: false,
12518
+ lines: []
12519
+ });
12520
+ working.current = status.working;
12521
+ closing.current = status.closing === true;
12522
+ const [mode, setMode] = (0, react.useState)("idle");
12523
+ const [box, setBox] = (0, react.useState)();
12524
+ (0, react.useEffect)(() => {
12525
+ let raf;
12526
+ const follow = () => {
12527
+ const rect = anchor.getBoundingClientRect();
12528
+ setBox((current) => current && Math.abs(current.left - rect.left) < .5 && Math.abs(current.top - rect.top) < .5 && Math.abs(current.width - rect.width) < .5 ? current : {
12529
+ left: rect.left,
12530
+ top: rect.top,
12531
+ bottom: rect.bottom,
12532
+ width: rect.width,
12533
+ docked: rect.bottom > window.innerHeight - 180
12534
+ });
12535
+ raf = requestAnimationFrame(follow);
12536
+ };
12537
+ follow();
12538
+ return () => cancelAnimationFrame(raf);
12539
+ }, [anchor]);
12540
+ (0, react.useEffect)(() => {
12541
+ if (!call) return void 0;
12542
+ const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
12543
+ const painter = canvas.current ? createOrb(canvas.current, accent) : void 0;
12544
+ const started = performance.now();
12545
+ let level = 0;
12546
+ let last = "";
12547
+ let closeSince = 0;
12548
+ let quietSince = 0;
12549
+ const tick = () => {
12550
+ const { mic, assistant } = call.levels();
12551
+ if (closing.current) {
12552
+ const now = performance.now();
12553
+ closeSince ||= now;
12554
+ if (assistant > .03) quietSince = 0;
12555
+ else quietSince ||= now;
12556
+ if (now - closeSince > 15e3 || now - closeSince > 1800 && now - quietSince > 1300) {
12557
+ closing.current = false;
12558
+ call.stop();
12559
+ return;
12560
+ }
12561
+ }
12562
+ const target = Math.max(mic, assistant);
12563
+ level += (target - level) * (target > level ? .35 : .12);
12564
+ orb.current?.style.setProperty("--level", reduce ? "0" : level.toFixed(3));
12565
+ painter?.draw((performance.now() - started) / 1e3, {
12566
+ mic,
12567
+ assistant,
12568
+ working: working.current,
12569
+ reduce
12570
+ });
12571
+ const next = assistant > .05 ? "speaking" : mic > .05 ? "listening" : "idle";
12572
+ if (next !== last) {
12573
+ last = next;
12574
+ setMode(next);
12575
+ }
12576
+ frame.current = requestAnimationFrame(tick);
12577
+ };
12578
+ tick();
12579
+ return () => {
12580
+ cancelAnimationFrame(frame.current);
12581
+ painter?.dispose();
12582
+ };
12583
+ }, [call]);
12584
+ (0, react.useEffect)(() => {
12585
+ if (!call) return void 0;
12586
+ let stopped = false;
12587
+ let seen = false;
12588
+ const poll = async () => {
12589
+ try {
12590
+ const result = await rpc.call(CHANNEL, "voice/status", { sessionId });
12591
+ if (!stopped && result.ok) {
12592
+ setStatus(result.value);
12593
+ if (result.value.active) seen = true;
12594
+ else if (seen) {
12595
+ stopped = true;
12596
+ call.stop();
12597
+ }
12598
+ }
12599
+ } catch {}
12600
+ };
12601
+ poll();
12602
+ const timer = setInterval(poll, 900);
12603
+ return () => {
12604
+ stopped = true;
12605
+ clearInterval(timer);
12606
+ };
12607
+ }, [
12608
+ call,
12609
+ rpc,
12610
+ sessionId
12611
+ ]);
12612
+ if (!box) return null;
12613
+ const label = connecting ? t("voiceConnecting") : status.working ? t("voiceWorking") : mode === "speaking" ? t("voiceSpeaking") : t("voiceListening");
12614
+ const lines = status.lines.slice(-2);
12615
+ return (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12616
+ className: "codexVoiceStage",
12617
+ role: "status",
12618
+ "aria-live": "polite",
12619
+ "data-side": box.docked ? "above" : "below",
12620
+ style: {
12621
+ left: box.left + box.width / 2,
12622
+ top: box.docked ? box.top : box.bottom,
12623
+ "--voice-accent": accent
12624
+ },
12625
+ children: [
12626
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12627
+ className: "codexVoiceLines",
12628
+ children: lines.map((line, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12629
+ "data-role": line.role,
12630
+ "data-old": index < lines.length - 1 || void 0,
12631
+ children: line.text
12632
+ }, `${index}-${line.text.slice(0, 12)}`))
12633
+ }),
12634
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12635
+ className: "codexVoiceStatus",
12636
+ children: label
12637
+ }),
12638
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12639
+ className: "codexVoiceOrbBox",
12640
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12641
+ className: "codexVoiceDot",
12642
+ "data-gone": !connecting || void 0
12643
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12644
+ className: "codexVoiceOrb",
12645
+ ref: orb,
12646
+ "data-ready": !connecting,
12647
+ "data-mode": status.working ? "working" : mode,
12648
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("canvas", {
12649
+ ref: canvas,
12650
+ width: 240,
12651
+ height: 240,
12652
+ "aria-hidden": "true"
12653
+ })
12654
+ })]
12655
+ })
12656
+ ]
12657
+ }), document.body);
12658
+ }
12659
+ /**
12660
+ * The composer's voice button. It sits exactly on the send button while there is nothing to send (the send button is
12661
+ * disabled) and gives it back as soon as there is text, so the one place always does the likely thing. During a call
12662
+ * it becomes the end button and, where DSH's dictation button is, a speaker and a microphone switch appear.
12663
+ */
12664
+ function VoiceCallButton({ sessionId, rpc, preference, t }) {
12665
+ const snapshot = usePreferenceSnapshot(preference);
12666
+ const marker = (0, react.useRef)(null);
12667
+ const call = (0, react.useRef)(null);
12668
+ const [liveCall, setLiveCall] = (0, react.useState)(null);
12669
+ const accent = (0, react.useRef)("");
12670
+ const button = (0, react.useRef)(null);
12671
+ const [place, setPlace] = (0, react.useState)();
12672
+ const [state, setState] = (0, react.useState)("idle");
12673
+ const [problem, setProblem] = (0, react.useState)("");
12674
+ const [micOff, setMicOff] = (0, react.useState)(false);
12675
+ const [speakerOff, setSpeakerOff] = (0, react.useState)(false);
12676
+ const enabled = snapshot.status === "ready" && snapshot.voiceCall === "on";
12677
+ (0, react.useLayoutEffect)(() => {
12678
+ if (!enabled) {
12679
+ setPlace(void 0);
12680
+ return;
12681
+ }
12682
+ const trailing = marker.current?.closest("[data-slot]")?.parentElement?.parentElement;
12683
+ if (!trailing) return void 0;
12684
+ const wasStatic = getComputedStyle(trailing).position === "static";
12685
+ if (wasStatic) trailing.style.position = "relative";
12686
+ const watcher = new MutationObserver(() => measure());
12687
+ const measure = () => {
12688
+ const send = [...trailing.children].filter((child) => child.tagName === "BUTTON" && !child.classList.contains("codexVoiceCall")).at(-1);
12689
+ if (!send) {
12690
+ setPlace(void 0);
12691
+ return;
12692
+ }
12693
+ const host = trailing.getBoundingClientRect();
12694
+ const box = send.getBoundingClientRect();
12695
+ const ratio = window.devicePixelRatio || 1;
12696
+ const snap = (value) => Math.round(value * ratio) / ratio;
12697
+ setPlace({
12698
+ host: trailing,
12699
+ activity: trailing.querySelector("[data-slot=\"conversation.input.activity\"]")?.parentElement ?? null,
12700
+ left: snap(box.left - host.left - trailing.clientLeft),
12701
+ top: snap(box.top - host.top - trailing.clientTop),
12702
+ width: snap(box.width),
12703
+ height: snap(box.width),
12704
+ idle: send.disabled,
12705
+ className: send.className
12706
+ });
12707
+ };
12708
+ measure();
12709
+ watcher.observe(trailing, {
12710
+ subtree: true,
12711
+ childList: true,
12712
+ attributes: true,
12713
+ attributeFilter: [
12714
+ "disabled",
12715
+ "aria-label",
12716
+ "class"
12717
+ ]
12718
+ });
12719
+ const resizer = new ResizeObserver(measure);
12720
+ resizer.observe(trailing);
12721
+ return () => {
12722
+ watcher.disconnect();
12723
+ resizer.disconnect();
12724
+ if (wasStatic) trailing.style.position = "";
12725
+ };
12726
+ }, [enabled]);
12727
+ const live = state === "live";
12728
+ (0, react.useEffect)(() => {
12729
+ const activity = place?.activity;
12730
+ if (!activity || !live) return void 0;
12731
+ activity.setAttribute("data-voice-live", "");
12732
+ return () => activity.removeAttribute("data-voice-live");
12733
+ }, [place?.activity, live]);
12734
+ (0, react.useEffect)(() => () => {
12735
+ call.current?.stop();
12736
+ }, []);
12737
+ (0, react.useEffect)(() => {
12738
+ if (!problem) return void 0;
12739
+ const timer = setTimeout(() => setProblem(""), 6e3);
12740
+ return () => clearTimeout(timer);
12741
+ }, [problem]);
12742
+ const start = async () => {
12743
+ setProblem("");
12744
+ accent.current = button.current ? getComputedStyle(button.current).backgroundColor : "";
12745
+ setMicOff(false);
12746
+ setSpeakerOff(false);
12747
+ setState("connecting");
12748
+ try {
12749
+ call.current = await openVoiceCall({
12750
+ rpc,
12751
+ sessionId,
12752
+ onEnd: () => {
12753
+ call.current = null;
12754
+ setLiveCall(null);
12755
+ setState("idle");
12756
+ }
12757
+ });
12758
+ setLiveCall(call.current);
12759
+ setState("live");
12760
+ } catch (error) {
12761
+ call.current = null;
12762
+ setLiveCall(null);
12763
+ setState("idle");
12764
+ setProblem(error?.name === "NotAllowedError" ? t("voiceMicBlocked") : t("voiceFailed"));
12765
+ }
12766
+ };
12767
+ const click = () => {
12768
+ if (state === "live") call.current?.stop();
12769
+ else if (state === "idle") start();
12770
+ };
12771
+ const anchor = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
12772
+ ref: marker,
12773
+ hidden: true
12774
+ });
12775
+ if (!enabled || !place) return anchor;
12776
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
12777
+ anchor,
12778
+ state !== "idle" || place.idle ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
12779
+ ref: button,
12780
+ type: "button",
12781
+ className: `${place.className} codexVoiceCall`,
12782
+ "data-state": state,
12783
+ onClick: click,
12784
+ disabled: state === "connecting",
12785
+ "aria-label": t(live ? "voiceEnd" : "voiceStart"),
12786
+ title: t(live ? "voiceEnd" : "voiceStart"),
12787
+ style: {
12788
+ left: place.left,
12789
+ top: place.top,
12790
+ width: place.width,
12791
+ height: place.height
12792
+ },
12793
+ children: live ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Cross, {}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bars, {})
12794
+ }), problem ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
12795
+ className: "codexVoiceCallNote",
12796
+ role: "alert",
12797
+ style: { right: 0 },
12798
+ children: problem
12799
+ }) : null] }), place.host) : null,
12800
+ live && place.activity && liveCall ? (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
12801
+ className: "codexVoiceTools",
12802
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
12803
+ type: "button",
12804
+ className: "codexVoiceTool",
12805
+ "aria-pressed": speakerOff,
12806
+ "aria-label": t(speakerOff ? "voiceUnmuteSpeaker" : "voiceMuteSpeaker"),
12807
+ title: t(speakerOff ? "voiceUnmuteSpeaker" : "voiceMuteSpeaker"),
12808
+ onClick: () => {
12809
+ liveCall.setOutputMuted(!speakerOff);
12810
+ setSpeakerOff(!speakerOff);
12811
+ },
12812
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Speaker, { off: speakerOff })
12813
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
12814
+ type: "button",
12815
+ className: "codexVoiceTool",
12816
+ "aria-pressed": micOff,
12817
+ "aria-label": t(micOff ? "voiceUnmute" : "voiceMute"),
12818
+ title: t(micOff ? "voiceUnmute" : "voiceMute"),
12819
+ onClick: () => {
12820
+ liveCall.setMuted(!micOff);
12821
+ setMicOff(!micOff);
12822
+ },
12823
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Mic, { off: micOff })
12824
+ })]
12825
+ }), place.activity) : null,
12826
+ state !== "idle" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(VoiceStage, {
12827
+ call: liveCall,
12828
+ connecting: state === "connecting",
12829
+ rpc,
12830
+ sessionId,
12831
+ anchor: place.host.parentElement?.parentElement ?? place.host,
12832
+ accent: accent.current,
12833
+ t
12834
+ }) : null
12835
+ ] });
12836
+ }
12837
+ /** One settings row: the label on the left, a menu in the same style as the context selector on the right. */
12838
+ function ChoiceRow({ label, items, selectedId, disabled, onSelect, trailing = null }) {
12839
+ const [open, setOpen] = (0, react.useState)(false);
12840
+ const selected = items.flatMap((item) => [item, ...item.submenu ?? []]).find((item) => item.id === selectedId)?.label ?? items[0].label;
12841
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12842
+ className: "codexSubscriptionPreference",
12843
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12844
+ className: "codexSubscriptionPreferenceCopy",
12845
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
12846
+ className: "codexSubscriptionPreferenceLabel",
12847
+ children: label
12848
+ })
12849
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12850
+ className: "codexVoiceChoice",
12851
+ children: [trailing, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Menu, {
12852
+ open,
12853
+ items,
12854
+ selectedId,
12855
+ onSelect: (value) => {
12856
+ setOpen(false);
12857
+ onSelect(value);
12858
+ },
12859
+ onClose: () => setOpen(false),
12860
+ align: "end",
12861
+ side: "bottom",
12862
+ portal: true,
12863
+ compact: true,
12864
+ anchor: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
12865
+ className: "codexSubscriptionContextTrigger",
12866
+ type: "button",
12867
+ "aria-label": label,
12868
+ "aria-haspopup": "menu",
12869
+ "aria-expanded": open,
12870
+ disabled,
12871
+ onClick: () => setOpen((value) => !value),
12872
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: selected }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconChevronDownOutline14, {})]
12873
+ })
12874
+ })]
12875
+ })]
12876
+ });
12877
+ }
12878
+ /** Settings for the composer's voice button: on or off, the voice (with a short sample to listen to) and the answer language. */
12879
+ function VoiceCallCard({ rpc, preference, snapshot, t }) {
12880
+ const audio = (0, react.useRef)();
12881
+ const alive = (0, react.useRef)(false);
12882
+ const [offered, setOffered] = (0, react.useState)();
12883
+ const [sample, setSample] = (0, react.useState)({
12884
+ state: "idle",
12885
+ note: ""
12886
+ });
12887
+ const on = snapshot.voiceCall === "on";
12888
+ (0, react.useEffect)(() => {
12889
+ alive.current = true;
12890
+ return () => {
12891
+ alive.current = false;
12892
+ audio.current?.pause();
12893
+ };
12894
+ }, []);
12895
+ (0, react.useEffect)(() => {
12896
+ if (!on) return;
12897
+ (async () => {
12898
+ try {
12899
+ const result = await rpc.call(CHANNEL, "voice/catalog", {});
12900
+ if (alive.current && result.ok) setOffered(result.value.voices);
12901
+ } catch {}
12902
+ })();
12903
+ }, [on]);
12904
+ /** Play a short clip of a voice; picking a voice plays it too, so it can be heard before it is used. */
12905
+ const playVoice = async (voice) => {
12906
+ audio.current?.pause();
12907
+ setSample({
12908
+ state: "loading",
12909
+ note: ""
12910
+ });
12911
+ try {
12912
+ const result = await rpc.call(CHANNEL, "voice/preview", { voice });
12913
+ if (!alive.current) return;
12914
+ if (!result.ok) {
12915
+ setSample({
12916
+ state: "missing",
12917
+ note: ""
12918
+ });
12919
+ return;
12920
+ }
12921
+ const clip = new Audio(result.value.audio);
12922
+ audio.current = clip;
12923
+ clip.onended = () => {
12924
+ if (alive.current) setSample((current) => ({
12925
+ ...current,
12926
+ state: "idle"
12927
+ }));
12928
+ };
12929
+ setSample({
12930
+ state: "playing",
12931
+ note: [result.value.description, result.value.accent].filter(Boolean).join(" · ")
12932
+ });
12933
+ await clip.play();
12934
+ } catch {
12935
+ if (alive.current) setSample({
12936
+ state: "missing",
12937
+ note: ""
12938
+ });
12939
+ }
12940
+ };
12941
+ const listed = VOICE_VOICES.filter((value) => offered ? offered.includes(value) : VOICE_VOICES.indexOf(value) < 9);
12942
+ const others = VOICE_VOICES.filter((value) => !listed.includes(value));
12943
+ const voices = [...listed.map((value) => ({
12944
+ id: value,
12945
+ label: value
12946
+ })), ...others.length === 0 ? [] : [{
12947
+ type: "separator",
12948
+ id: "more-line"
12949
+ }, {
12950
+ id: "more",
12951
+ label: t("voiceMore"),
12952
+ submenu: others.map((value) => ({
12953
+ id: value,
12954
+ label: value
12955
+ }))
12956
+ }]];
12957
+ const languages = VOICE_LANGUAGES.map((value) => ({
12958
+ id: value,
12959
+ label: value === "auto" ? t("voiceAuto") : t(`voiceLang_${value}`)
12960
+ }));
12961
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
12962
+ className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
12963
+ "aria-label": t("voiceTitle"),
12964
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12965
+ className: "codexSubscriptionPreference",
12966
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12967
+ className: "codexSubscriptionPreferenceCopy",
12968
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
12969
+ className: "codexSubscriptionPreferenceLabel",
12970
+ children: [
12971
+ t("voiceTitle"),
12972
+ " ",
12973
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: "Beta" })
12974
+ ]
12975
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Hint, {
12976
+ t,
12977
+ children: t("voiceHint")
12978
+ })]
12979
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
12980
+ className: "codexSubscriptionQuotaModes",
12981
+ role: "radiogroup",
12982
+ "aria-label": t("voiceTitle"),
12983
+ "aria-busy": snapshot.saving || void 0,
12984
+ children: ["off", "on"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
12985
+ className: "codexSubscriptionQuotaMode",
12986
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
12987
+ type: "radio",
12988
+ name: "codex-voice-call",
12989
+ checked: snapshot.voiceCall === value,
12990
+ disabled: !snapshot.writable,
12991
+ onChange: () => {
12992
+ preference.set({ [VOICE_CALL_FIELD]: value });
12993
+ }
12994
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`remote_${value}`) })]
12995
+ }, value))
12996
+ })]
12997
+ }), on ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
12998
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: "codexSubscriptionDivider" }),
12999
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChoiceRow, {
13000
+ label: t("voiceVoice"),
13001
+ disabled: !snapshot.writable,
13002
+ selectedId: snapshot.voiceVoice,
13003
+ items: voices,
13004
+ onSelect: (value) => {
13005
+ if (value === "more") return;
13006
+ preference.set({ [VOICE_VOICE_FIELD]: value });
13007
+ playVoice(value);
13008
+ },
13009
+ trailing: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
13010
+ className: "codexSubscriptionContextTrigger",
13011
+ type: "button",
13012
+ disabled: sample.state === "loading",
13013
+ onClick: () => {
13014
+ playVoice(snapshot.voiceVoice);
13015
+ },
13016
+ children: sample.state === "loading" ? t("voiceLoading") : t("voicePlay")
13017
+ })
13018
+ }),
13019
+ sample.state === "playing" && sample.note ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
13020
+ className: "codexSubscriptionHelp",
13021
+ role: "status",
13022
+ children: sample.note
13023
+ }) : null,
13024
+ sample.state === "missing" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
13025
+ className: "codexSubscriptionHelp",
13026
+ role: "status",
13027
+ children: t("voiceNoSample")
13028
+ }) : null,
13029
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChoiceRow, {
13030
+ label: t("voiceLanguage"),
13031
+ disabled: !snapshot.writable,
13032
+ selectedId: snapshot.voiceLanguage,
13033
+ items: languages,
13034
+ onSelect: (value) => {
13035
+ preference.set({ [VOICE_LANGUAGE_FIELD]: value });
13036
+ }
13037
+ })
13038
+ ] }) : null]
10049
13039
  });
10050
13040
  }
10051
13041
  //#endregion
@@ -12943,9 +15933,9 @@ window.__ModuleLoader__.load({
12943
15933
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
12944
15934
  role: "status",
12945
15935
  children: [
12946
- t(STATUS_KEYS[status] ?? "remoteConnecting"),
15936
+ status === "connected" && state?.phones > 0 ? t("remotePhones").replace("{count}", String(state.phones)) : t(STATUS_KEYS[status] ?? "remoteConnecting"),
12947
15937
  status === "error" && state?.lastError ? ` · ${state.lastError}` : "",
12948
- state?.phones > 0 ? ` · ${t("remotePhones").replace("{count}", String(state.phones))}` : ""
15938
+ status !== "connected" && state?.phones > 0 ? ` · ${t("remotePhones").replace("{count}", String(state.phones))}` : ""
12949
15939
  ]
12950
15940
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
12951
15941
  type: "button",
@@ -12957,6 +15947,11 @@ window.__ModuleLoader__.load({
12957
15947
  children: t(pairing ? "remotePairAgain" : "remotePair")
12958
15948
  })]
12959
15949
  }),
15950
+ status === "waiting" && state?.lastError === "conflict" && state?.reconnects >= 6 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
15951
+ role: "status",
15952
+ className: "codexSubscriptionHelp",
15953
+ children: t("remoteConflictLong")
15954
+ }) : null,
12960
15955
  failed ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12961
15956
  role: "alert",
12962
15957
  className: "codexSubscriptionHelp",
@@ -13281,7 +16276,7 @@ window.__ModuleLoader__.load({
13281
16276
  const snapshot = usePreferenceSnapshot(preference);
13282
16277
  const writable = snapshot.status === "ready" && snapshot.writable === true;
13283
16278
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
13284
- className: "codexSubscriptionPreference codexSubscriptionPreferenceStack",
16279
+ className: "codexSubscriptionPreference codexSubscriptionConnectors",
13285
16280
  children: [
13286
16281
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
13287
16282
  className: "codexSubscriptionPreferenceCopy",
@@ -13594,7 +16589,8 @@ window.__ModuleLoader__.load({
13594
16589
  function PreferencesCard({ preference, rpc, t, defaultModel, section = "display" }) {
13595
16590
  const snapshot = usePreferenceSnapshot(preference);
13596
16591
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
13597
- className: section === "advanced" ? "codexSubscriptionAdvancedPreferences" : "codexSubscriptionCard codexSubscriptionPreferencesCard",
16592
+ className: section === "advanced" || section === "interop" ? "codexSubscriptionAdvancedPreferences" : "codexSubscriptionCard codexSubscriptionPreferencesCard",
16593
+ "data-others-off": section === "interop" && snapshot.otherModels === "off" ? "true" : void 0,
13598
16594
  children: [
13599
16595
  snapshot.restartRequired ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
13600
16596
  className: "codexSubscriptionError",
@@ -13640,21 +16636,9 @@ window.__ModuleLoader__.load({
13640
16636
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RetryPolicyPreference, {
13641
16637
  preference,
13642
16638
  t
13643
- }),
13644
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConnectorsPreference, {
13645
- preference,
13646
- t
13647
16639
  })
13648
16640
  ]
13649
16641
  }),
13650
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
13651
- className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
13652
- "aria-label": t("searchSectionTitle"),
13653
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", { children: t("searchSectionTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchProviderPreference, {
13654
- preference,
13655
- t
13656
- })]
13657
- }),
13658
16642
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
13659
16643
  className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
13660
16644
  "aria-label": t("connectionTitle"),
@@ -13702,7 +16686,7 @@ window.__ModuleLoader__.load({
13702
16686
  }),
13703
16687
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("section", {
13704
16688
  className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
13705
- "aria-label": t("reviewModelTitle"),
16689
+ "aria-label": t("compactionTitle"),
13706
16690
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
13707
16691
  className: "codexSubscriptionPreference",
13708
16692
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -13710,43 +16694,90 @@ window.__ModuleLoader__.load({
13710
16694
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
13711
16695
  className: "codexSubscriptionPreferenceLabel",
13712
16696
  children: [
13713
- t("reviewModelTitle"),
16697
+ t("compactionTitle"),
13714
16698
  " ",
13715
16699
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: "Beta" })
13716
16700
  ]
13717
16701
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Hint, {
13718
16702
  t,
13719
- children: t("reviewModelHint")
16703
+ children: t("compactionHint")
13720
16704
  })]
13721
16705
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
13722
16706
  className: "codexSubscriptionQuotaModes",
13723
16707
  role: "radiogroup",
13724
- "aria-label": t("reviewModelTitle"),
16708
+ "aria-label": t("compactionTitle"),
13725
16709
  "aria-busy": snapshot.saving || void 0,
13726
- children: ["session", "official"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
16710
+ children: ["dsh", "cloud"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
13727
16711
  className: "codexSubscriptionQuotaMode",
13728
16712
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
13729
16713
  type: "radio",
13730
- name: "codex-review-model",
13731
- checked: snapshot.reviewModel === value,
16714
+ name: "codex-compaction-mode",
16715
+ checked: snapshot.compactionMode === value,
13732
16716
  disabled: !snapshot.writable,
13733
16717
  onChange: () => {
13734
- preference.set({ reviewModel: value });
16718
+ preference.set({ compactionMode: value });
13735
16719
  }
13736
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`reviewModel_${value}`) })]
16720
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`compaction_${value}`) })]
16721
+ }, value))
16722
+ })]
16723
+ })
16724
+ })
16725
+ ] }) : section === "interop" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
16726
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("section", {
16727
+ className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
16728
+ "aria-label": t("otherModelsTitle"),
16729
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
16730
+ className: "codexSubscriptionPreference",
16731
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
16732
+ className: "codexSubscriptionPreferenceCopy",
16733
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
16734
+ className: "codexSubscriptionPreferenceLabel",
16735
+ children: t("otherModelsTitle")
16736
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Hint, {
16737
+ t,
16738
+ children: t("otherModelsHint")
16739
+ })]
16740
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
16741
+ className: "codexSubscriptionQuotaModes",
16742
+ role: "radiogroup",
16743
+ "aria-label": t("otherModelsTitle"),
16744
+ "aria-busy": snapshot.saving || void 0,
16745
+ children: ["on", "off"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
16746
+ className: "codexSubscriptionQuotaMode",
16747
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
16748
+ type: "radio",
16749
+ name: "codex-other-models",
16750
+ checked: snapshot.otherModels === value,
16751
+ disabled: !snapshot.writable,
16752
+ onChange: () => {
16753
+ preference.set({ otherModels: value });
16754
+ }
16755
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`otherModels_${value}`) })]
13737
16756
  }, value))
13738
16757
  })]
13739
16758
  })
13740
16759
  }),
13741
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RemoteControlCard, {
13742
- rpc,
13743
- preference,
13744
- snapshot,
13745
- t
16760
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("section", {
16761
+ className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
16762
+ "data-governed": "true",
16763
+ "aria-label": t("searchSectionTitle"),
16764
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchProviderPreference, {
16765
+ preference,
16766
+ t
16767
+ })
13746
16768
  }),
13747
16769
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("section", {
13748
16770
  className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
13749
- "aria-label": t("compactionTitle"),
16771
+ "data-governed": "true",
16772
+ "aria-label": t("connectors"),
16773
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConnectorsPreference, {
16774
+ preference,
16775
+ t
16776
+ })
16777
+ }),
16778
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("section", {
16779
+ className: "codexSubscriptionCard codexSubscriptionPreferencesCard",
16780
+ "aria-label": t("reviewModelTitle"),
13750
16781
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
13751
16782
  className: "codexSubscriptionPreference",
13752
16783
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -13754,30 +16785,30 @@ window.__ModuleLoader__.load({
13754
16785
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
13755
16786
  className: "codexSubscriptionPreferenceLabel",
13756
16787
  children: [
13757
- t("compactionTitle"),
16788
+ t("reviewModelTitle"),
13758
16789
  " ",
13759
16790
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: "Beta" })
13760
16791
  ]
13761
16792
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Hint, {
13762
16793
  t,
13763
- children: t("compactionHint")
16794
+ children: t("reviewModelHint")
13764
16795
  })]
13765
16796
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
13766
16797
  className: "codexSubscriptionQuotaModes",
13767
16798
  role: "radiogroup",
13768
- "aria-label": t("compactionTitle"),
16799
+ "aria-label": t("reviewModelTitle"),
13769
16800
  "aria-busy": snapshot.saving || void 0,
13770
- children: ["dsh", "cloud"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
16801
+ children: ["session", "official"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
13771
16802
  className: "codexSubscriptionQuotaMode",
13772
16803
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
13773
16804
  type: "radio",
13774
- name: "codex-compaction-mode",
13775
- checked: snapshot.compactionMode === value,
16805
+ name: "codex-review-model",
16806
+ checked: snapshot.reviewModel === value,
13776
16807
  disabled: !snapshot.writable,
13777
16808
  onChange: () => {
13778
- preference.set({ compactionMode: value });
16809
+ preference.set({ reviewModel: value });
13779
16810
  }
13780
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`compaction_${value}`) })]
16811
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`reviewModel_${value}`) })]
13781
16812
  }, value))
13782
16813
  })]
13783
16814
  })
@@ -13823,6 +16854,18 @@ window.__ModuleLoader__.load({
13823
16854
  preference,
13824
16855
  t
13825
16856
  })]
16857
+ }),
16858
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(VoiceCallCard, {
16859
+ rpc,
16860
+ preference,
16861
+ snapshot,
16862
+ t
16863
+ }),
16864
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RemoteControlCard, {
16865
+ rpc,
16866
+ preference,
16867
+ snapshot,
16868
+ t
13826
16869
  })
13827
16870
  ] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
13828
16871
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuickQuotaPreference, {
@@ -14504,6 +17547,13 @@ window.__ModuleLoader__.load({
14504
17547
  };
14505
17548
  }
14506
17549
  //#endregion
17550
+ //#region src/diagnostic-log-format.js
17551
+ function formatLogLine(entry) {
17552
+ const stamp = new Date(entry.time).toISOString().replace("T", " ").slice(0, 19);
17553
+ const repeat = entry.count > 1 ? ` (x${entry.count})` : "";
17554
+ return `${stamp} ${entry.level.toUpperCase().padEnd(5)} [${entry.area}] ${entry.message}${entry.detail ? ` — ${entry.detail}` : ""}${repeat}`;
17555
+ }
17556
+ //#endregion
14507
17557
  //#region src/diagnostic-compact.js
14508
17558
  function compactDiagnostic(report) {
14509
17559
  const summary = report.summary ?? { findings: [] };
@@ -14534,17 +17584,29 @@ window.__ModuleLoader__.load({
14534
17584
  reason: item.reason,
14535
17585
  ...item.latest ? { latest: `${item.latest.action} ${item.latest.status}` } : { latest: "not-verified" }
14536
17586
  })),
17587
+ log: (report.log?.entries ?? []).slice(-150).map(formatLogLine),
14537
17588
  ...report.client?.status === "unknown" ? { hostCollected: false } : {}
14538
17589
  };
14539
17590
  }
14540
17591
  //#endregion
14541
17592
  //#region src/client-diagnostics.jsx
17593
+ const LEVELS = {
17594
+ all: [
17595
+ "info",
17596
+ "warn",
17597
+ "error"
17598
+ ],
17599
+ warn: ["warn", "error"],
17600
+ error: ["error"]
17601
+ };
14542
17602
  function DiagnosticsCard({ rpc, t, diagnostics }) {
14543
17603
  const [report, setReport] = (0, react.useState)();
14544
17604
  const [busy, setBusy] = (0, react.useState)(false);
14545
17605
  const [copied, setCopied] = (0, react.useState)(false);
14546
17606
  const [error, setError] = (0, react.useState)(false);
14547
17607
  const [copyError, setCopyError] = (0, react.useState)(false);
17608
+ const [level, setLevel] = (0, react.useState)("all");
17609
+ const [logCopied, setLogCopied] = (0, react.useState)(false);
14548
17610
  const load = () => {
14549
17611
  setBusy(true);
14550
17612
  setError(false);
@@ -14567,6 +17629,10 @@ window.__ModuleLoader__.load({
14567
17629
  setCopyError(false);
14568
17630
  Promise.resolve().then(() => navigator.clipboard.writeText(JSON.stringify(full ? report : compactDiagnostic(report), null, 2))).then(() => setCopied(true)).catch(() => setCopyError(true));
14569
17631
  };
17632
+ const lines = (report?.log?.entries ?? []).filter((entry) => LEVELS[level].includes(entry.level));
17633
+ const copyLog = () => {
17634
+ Promise.resolve().then(() => navigator.clipboard.writeText(lines.map(formatLogLine).join(String.fromCharCode(10)))).then(() => setLogCopied(true)).catch(() => setCopyError(true));
17635
+ };
14570
17636
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
14571
17637
  className: "codexSubscriptionCard codexSubscriptionDiagnostics",
14572
17638
  children: [
@@ -14605,10 +17671,6 @@ window.__ModuleLoader__.load({
14605
17671
  })]
14606
17672
  }),
14607
17673
  report === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
14608
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
14609
- className: "codexSubscriptionHelp",
14610
- children: t("diagnosticsCoverageHint")
14611
- }),
14612
17674
  report.generatedAt ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
14613
17675
  className: "codexSubscriptionHelp",
14614
17676
  children: [
@@ -14636,22 +17698,54 @@ window.__ModuleLoader__.load({
14636
17698
  ] }, `${event.source}:${event.action}`)) }) : null
14637
17699
  ] }, item.code)) }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("diagnosticsNoRecordedFailure") })
14638
17700
  }),
14639
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
14640
- style: {
14641
- width: "100%",
14642
- fontSize: 12,
14643
- textAlign: "left",
14644
- borderSpacing: "0 8px"
14645
- },
14646
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
14647
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsCapability") }),
14648
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsReadiness") }),
14649
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsEvidence") })
14650
- ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: (report.inspection?.capabilities ?? []).map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
14651
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: t(`diagnosticCapability_${item.id}`) }),
14652
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", { children: [t(`diagnosticReason_${item.reason}`), item.blockedBy ? ` · ${t(`diagnosticCapability_${item.blockedBy}`)}` : ""] }),
14653
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", { children: [item.latest ? `${item.latest.action} · ${t(`diagnosticSource_${item.latest.source}`)} · ${t(`diagnosticOutcome_${item.latest.status}`)} · ${new Date(item.latest.observedAt).toLocaleTimeString(uiLocale())}` : t("diagnosticsUnverified"), item.unresolved?.length ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("diagnosticsUnresolved") }) : null] })
14654
- ] }, item.id)) })]
17701
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
17702
+ className: "codexSubscriptionLogHead",
17703
+ children: [
17704
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", { children: t("diagnosticsLog") }),
17705
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
17706
+ className: "codexSubscriptionQuotaModes",
17707
+ role: "radiogroup",
17708
+ "aria-label": t("diagnosticsLog"),
17709
+ children: Object.keys(LEVELS).map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
17710
+ className: "codexSubscriptionQuotaMode",
17711
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
17712
+ type: "radio",
17713
+ name: "codex-log-level",
17714
+ checked: level === value,
17715
+ onChange: () => {
17716
+ setLevel(value);
17717
+ setLogCopied(false);
17718
+ }
17719
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(`logLevel_${value}`) })]
17720
+ }, value))
17721
+ }),
17722
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
17723
+ type: "button",
17724
+ variant: "outline",
17725
+ disabled: lines.length === 0,
17726
+ onClick: copyLog,
17727
+ children: logCopied ? t("logCopied") : t("logCopy")
17728
+ })
17729
+ ]
17730
+ }),
17731
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
17732
+ className: "codexSubscriptionHelp",
17733
+ children: t("diagnosticsLogHint")
17734
+ }),
17735
+ lines.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
17736
+ className: "codexSubscriptionHelp",
17737
+ children: t("logEmpty")
17738
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
17739
+ className: "codexSubscriptionLog",
17740
+ tabIndex: 0,
17741
+ children: lines.slice().reverse().map((entry) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
17742
+ className: `codexSubscriptionLogLine codexSubscriptionLog_${entry.level}`,
17743
+ children: [
17744
+ formatLogLine(entry),
17745
+ entry.earlier ? ` (${t("logEarlier")})` : "",
17746
+ String.fromCharCode(10)
17747
+ ]
17748
+ }, entry.sequence))
14655
17749
  }),
14656
17750
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
14657
17751
  className: "codexSubscriptionHelp",
@@ -14659,6 +17753,28 @@ window.__ModuleLoader__.load({
14659
17753
  }),
14660
17754
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", { children: [
14661
17755
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: t("diagnosticsDetails") }),
17756
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
17757
+ className: "codexSubscriptionHelp",
17758
+ children: t("diagnosticsCoverageHint")
17759
+ }),
17760
+ " ",
17761
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
17762
+ style: {
17763
+ width: "100%",
17764
+ fontSize: 12,
17765
+ textAlign: "left",
17766
+ borderSpacing: "0 8px"
17767
+ },
17768
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
17769
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsCapability") }),
17770
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsReadiness") }),
17771
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("diagnosticsEvidence") })
17772
+ ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: (report.inspection?.capabilities ?? []).map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
17773
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: t(`diagnosticCapability_${item.id}`) }),
17774
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", { children: [t(`diagnosticReason_${item.reason}`), item.blockedBy ? ` · ${t(`diagnosticCapability_${item.blockedBy}`)}` : ""] }),
17775
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", { children: [item.latest ? `${item.latest.action} · ${t(`diagnosticSource_${item.latest.source}`)} · ${t(`diagnosticOutcome_${item.latest.status}`)} · ${new Date(item.latest.observedAt).toLocaleTimeString(uiLocale())}` : t("diagnosticsUnverified"), item.unresolved?.length ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: t("diagnosticsUnresolved") }) : null] })
17776
+ ] }, item.id)) })]
17777
+ }),
14662
17778
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
14663
17779
  type: "button",
14664
17780
  variant: "outline",
@@ -15564,6 +18680,7 @@ window.__ModuleLoader__.load({
15564
18680
  const tabs = [
15565
18681
  "account",
15566
18682
  "advanced",
18683
+ "interop",
15567
18684
  "creative",
15568
18685
  "maintenance"
15569
18686
  ];
@@ -15654,6 +18771,18 @@ window.__ModuleLoader__.load({
15654
18771
  section: "advanced"
15655
18772
  })
15656
18773
  }),
18774
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
18775
+ role: "tabpanel",
18776
+ id: `${id}-interop`,
18777
+ "aria-labelledby": `${id}-interop-tab`,
18778
+ hidden: tab !== "interop",
18779
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreferencesCard, {
18780
+ rpc,
18781
+ preference,
18782
+ t,
18783
+ section: "interop"
18784
+ })
18785
+ }),
15657
18786
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
15658
18787
  role: "tabpanel",
15659
18788
  id: `${id}-creative`,
@@ -15851,6 +18980,7 @@ window.__ModuleLoader__.load({
15851
18980
  "uiConversation",
15852
18981
  "sessions"
15853
18982
  ];
18983
+ const ComposerRight = (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CodexComposerQuota, { ...props }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(VoiceCallButton, { ...props })] });
15854
18984
  function apply(ctx) {
15855
18985
  const diagnostics = createHostDiagnostics();
15856
18986
  ctx.effect(() => diagnostics.register(ctx.slots), "codex-subscription: host inspection");
@@ -15928,16 +19058,22 @@ window.__ModuleLoader__.load({
15928
19058
  order: 15,
15929
19059
  locale: NS,
15930
19060
  inject: (sessionId) => ({
19061
+ sessionId,
15931
19062
  preference,
15932
19063
  rpc,
15933
19064
  t,
15934
19065
  directory: modelDirectories.directoryFor(sessionId).store
15935
19066
  })
15936
- }, CodexComposerQuota));
19067
+ }, ComposerRight));
15937
19068
  scope.slots.inject("conversation.input.model", () => scope.slots.register({
15938
19069
  name: "conversation.input.model",
15939
19070
  priority: -10,
15940
19071
  locale: NS,
19072
+ children: { "conversation.input.model.label": {
19073
+ kind: "single",
19074
+ scope: "session",
19075
+ inline: true
19076
+ } },
15941
19077
  inject: (sessionId) => {
15942
19078
  const directory = modelDirectories.directoryFor(sessionId);
15943
19079
  const available = sessions.subagentAddress(sessionId) === void 0;