cozyclay 3.1.4 → 3.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/INSTALL_FOR_AGENTS.md +3 -0
  3. package/README.md +5 -0
  4. package/bin/agent/agent-failure-codes.mjs +31 -0
  5. package/bin/agent/agent-routes.mjs +5 -10
  6. package/bin/agent/agent-runner.mjs +5 -3
  7. package/bin/cozyclay.mjs +16 -64
  8. package/bin/studio-routes.mjs +69 -0
  9. package/bin/update-check.mjs +53 -5
  10. package/bin/update-install.mjs +136 -0
  11. package/bin/update-routes.mjs +80 -0
  12. package/dist/ai-camera-control/index.html +1 -1
  13. package/dist/app/index.html +5 -6
  14. package/dist/assets/{TaskBoard-U1Yl-4F1.js → TaskBoard-DwXhsJXz.js} +1 -1
  15. package/dist/assets/app-BLS1Zaru.js +5144 -0
  16. package/dist/assets/app-CEP7jzXB.css +1 -0
  17. package/dist/assets/compile-worker-or7djI2v.js +6 -0
  18. package/dist/assets/{motion3-compile-DDG3wklD.js → motion3-compile-Du7UXrWn.js} +1 -1
  19. package/dist/assets/scene-asset-sync-t45pWCyq.js +13 -0
  20. package/dist/assets/task-board-CkLZGPkv.js +15 -0
  21. package/dist/assets/workflow-DJwOUzqJ.js +179 -0
  22. package/dist/cozyclay-package.json +1 -1
  23. package/dist/greybox-to-video/index.html +3 -3
  24. package/dist/index.html +533 -264
  25. package/dist/media/cozyclay-mark.png +0 -0
  26. package/dist/media/cozyclay-truck-demo-poster.jpg +0 -0
  27. package/dist/media/step-move-poster.jpg +0 -0
  28. package/dist/media/step-shoot-poster.jpg +0 -0
  29. package/dist/media/step-stage-poster.jpg +0 -0
  30. package/dist/media/truck-greybox-poster.jpg +0 -0
  31. package/dist/media/truck-seedance-poster.jpg +0 -0
  32. package/dist/previs-software/index.html +4 -4
  33. package/dist/privacy/index.html +46 -19
  34. package/dist/seedance-camera-control/index.html +3 -3
  35. package/dist/sitemap.xml +6 -6
  36. package/dist/workflow/index.html +3 -4
  37. package/mcp/project-camera.mjs +43 -0
  38. package/package.json +2 -1
  39. package/src/App.jsx +59 -70
  40. package/src/analytics-controls.js +17 -0
  41. package/src/analytics-friction.js +124 -0
  42. package/src/analytics-strict.js +139 -0
  43. package/src/analytics-values.js +49 -0
  44. package/src/analytics.js +37 -133
  45. package/src/asset-pane.jsx +4 -5
  46. package/src/click-friction.js +101 -0
  47. package/src/command-bus-telemetry.js +155 -0
  48. package/src/command-bus.js +10 -8
  49. package/src/commands/motion3.js +7 -2
  50. package/src/controls.jsx +3 -2
  51. package/src/crash-telemetry.js +45 -0
  52. package/src/domains/cast.js +2 -11
  53. package/src/domains/motion.js +49 -38
  54. package/src/domains/objects.js +3 -0
  55. package/src/domains/scene-undo.js +27 -0
  56. package/src/domains/scenes.js +1 -1
  57. package/src/error-boundary.jsx +2 -0
  58. package/src/export-attempt.js +100 -0
  59. package/src/export-workspace.js +12 -1
  60. package/src/first-success-guide.jsx +11 -7
  61. package/src/guide-telemetry.js +60 -0
  62. package/src/hierarchy-panel.jsx +2 -1
  63. package/src/live-control.js +2 -9
  64. package/src/locale-zh/domains.js +1 -0
  65. package/src/main.jsx +5 -0
  66. package/src/motion/timeline.jsx +9 -5
  67. package/src/motion-draft-telemetry.js +62 -0
  68. package/src/motion3/compiler/channels.js +7 -5
  69. package/src/motion3/compiler/compile.js +6 -2
  70. package/src/motion3/compiler/finger-close.js +84 -7
  71. package/src/motion3/compiler/head-lead.js +70 -0
  72. package/src/motion3/compiler/head-steady.js +1 -1
  73. package/src/motion3/compiler/limbs.js +10 -3
  74. package/src/motion3/compiler/pose.js +1 -1
  75. package/src/motion3/compiler/validate.js +5 -3
  76. package/src/motion3/pipeline.js +4 -0
  77. package/src/motion3/qa/explain.js +2 -1
  78. package/src/motion3/qa/finger-checks.js +80 -0
  79. package/src/motion3/qa/gait-observe.js +88 -0
  80. package/src/motion3/qa/grasp-checks.js +3 -0
  81. package/src/motion3/qa/hints-grasp.js +8 -0
  82. package/src/motion3/qa/index.js +2 -1
  83. package/src/motion3/qa/motion-life.js +26 -3
  84. package/src/motion3/schema/topics.js +1 -1
  85. package/src/playback-telemetry.js +107 -0
  86. package/src/post-turn-edits.js +62 -0
  87. package/src/search-friction.js +49 -0
  88. package/src/semantic-edit.js +19 -6
  89. package/src/shell/BoardSlot.jsx +3 -3
  90. package/src/shell/BottomDock.jsx +1 -1
  91. package/src/shell/DetailsSlot.jsx +1 -1
  92. package/src/shell/MenuBar.jsx +13 -13
  93. package/src/shell/StudioShell.jsx +7 -1
  94. package/src/shell/TopBar.jsx +2 -0
  95. package/src/shell/ViewportToolbar.jsx +2 -2
  96. package/src/shortcut-friction.js +122 -0
  97. package/src/stage-canvas-rigs.jsx +3 -4
  98. package/src/studio-telemetry.js +97 -0
  99. package/src/thrash-friction.js +90 -0
  100. package/src/update/UpdateChip.jsx +86 -0
  101. package/src/update/UpdateDialog.jsx +147 -0
  102. package/src/update/update-client.js +188 -0
  103. package/src/update/update-telemetry.js +78 -0
  104. package/src/update/update.css +94 -0
  105. package/src/use-webgl-available.js +35 -0
  106. package/src/workflow/AgentPanel.jsx +29 -30
  107. package/src/workflow/CozySceneNode.jsx +1 -1
  108. package/src/workflow/LoginPanel.jsx +15 -5
  109. package/src/workflow/agent-client.js +10 -91
  110. package/src/workflow/agent-failure-codes.js +47 -0
  111. package/src/workflow/agent-turn-telemetry.js +222 -0
  112. package/src/workflow/connect-telemetry.js +86 -0
  113. package/src/workflow/prompt-telemetry.js +105 -0
  114. package/tools/dev/pages/privacy.html +44 -17
  115. package/tools/loc-baseline.json +10 -10
  116. package/tools/run-tests.mjs +8 -8
  117. package/tools/verify-package-tarball.mjs +29 -1
  118. package/dist/assets/app-BdRlMf4J.css +0 -1
  119. package/dist/assets/app-KXdgBC-S.js +0 -5144
  120. package/dist/assets/compile-worker-oy_P9HHh.js +0 -6
  121. package/dist/assets/landing-y3EqDgSZ.js +0 -1
  122. package/dist/assets/modulepreload-polyfill-P2Xu9kJm.js +0 -1
  123. package/dist/assets/scene-asset-sync-Bz59Ghdz.js +0 -13
  124. package/dist/assets/task-board-DFfNa0xg.js +0 -15
  125. package/dist/assets/workflow-BMJGd_gZ.js +0 -179
  126. package/dist/media/playground-poster.jpg +0 -0
@@ -4,6 +4,7 @@
4
4
  import { StudioProtocolError, StudioSchemas, validateStudioSchema, validateReceipt, validateStudioIdentity, refusalCode } from './studio-agent-protocol.js';
5
5
  import { agentTurnControls, markAgentTurn, turnEditPoint, recordTurnEdit, undoTurnEdit } from './agent-turn-mark.js';
6
6
  import { createBusTasks } from './bus-tasks.js';
7
+ import { createHistoryReceipts, noteRefusal, noteUndone } from './command-bus-telemetry.js';
7
8
 
8
9
  export { withCommandHistory } from './command-history.js';
9
10
 
@@ -16,7 +17,7 @@ export const isBusRunActive = () => activeRunDepth > 0;
16
17
 
17
18
  export function createCommandBus({ registry, ports }) {
18
19
  const pending = new Map(), transactions = new Map(), jobs = new Map(), listeners = new Set();
19
- const confirmations = new Map(), historyReceipts = new Map();
20
+ const confirmations = new Map(), historyReceipts = createHistoryReceipts(ports);
20
21
  let agentTurn = null;
21
22
  const tasks = createBusTasks({ ports, emit: event => emit(event) });
22
23
  function exposure(entry, args, request) {
@@ -218,6 +219,8 @@ export function createCommandBus({ registry, ports }) {
218
219
  agentTurn.session?.cancel({ restore: false }); agentTurn = null;
219
220
  }
220
221
  const turn = request.origin === 'agent' && request.turnId === agentTurn?.txId ? agentTurn : null, task = tasks.of(request, id);
222
+ // The command a transaction control runs (a drag's run.commit is its entry's), for telemetry.
223
+ const action = id === 'run.begin' ? args?.id : id.startsWith('run.') ? transactions.get(args?.txId)?.entry.id : undefined;
221
224
  const recordAction = (domain, invoke, targetId, nested = false) => {
222
225
  if (!turn) return ports.recordAction(domain, invoke, targetId, nested);
223
226
  // Enrol each owner in the existing composed session. Do not commit (or
@@ -228,10 +231,7 @@ export function createCommandBus({ registry, ports }) {
228
231
  };
229
232
  let begun = false, releaseToasts, timer, foregroundTimer, job, applied = false, committedHistoryId;
230
233
  const controller = new AbortController();
231
- const clearTimer = () => {
232
- if (timer !== undefined) clear(timer);
233
- if (foregroundTimer !== undefined) clear(foregroundTimer);
234
- };
234
+ const clearTimer = () => { if (timer !== undefined) clear(timer); if (foregroundTimer !== undefined) clear(foregroundTimer); };
235
235
  const toasts = [];
236
236
  const toastRefusal = () => toasts.length && ports.read().revision === before.revision ? new StudioProtocolError('TARGET_NOT_READY', toasts.at(-1).message) : null;
237
237
  const remember = value => {
@@ -241,8 +241,7 @@ export function createCommandBus({ registry, ports }) {
241
241
  value = validateReceipt({ ...value, commandId, jobId: job.id });
242
242
  }
243
243
  const recorded = journal.record(value);
244
- if (recorded.undo?.canUndoDirect && !id.startsWith('edit.')) historyReceipts.set(recorded.undo.historyEntryId, recorded);
245
- for (const [key, receipt] of historyReceipts) if (ports.isRetained?.(receipt) === false) historyReceipts.delete(key);
244
+ historyReceipts.remember(recorded, { id, origin: request.origin, action, args });
246
245
  ports.remember?.(recorded); return recorded;
247
246
  };
248
247
  const rejected = error => {
@@ -251,6 +250,8 @@ export function createCommandBus({ registry, ports }) {
251
250
  if (!(error instanceof StudioProtocolError)) error = toastRefusal() ?? error;
252
251
  if (request.origin === 'ui' && error.uiMessage) ports.showRefusal?.(error.uiMessage);
253
252
  const value = refusal(request, before, error, job ? applied : undefined);
253
+ // Session friction and studio:refused, by who asked and what (command-bus-telemetry.js).
254
+ noteRefusal(value, request.origin, action ?? id);
254
255
  const recorded = begun ? remember(value) : value;
255
256
  if (job && !job.completion) { job.outcome = recorded; job.completion = Promise.resolve(recorded); emit({ type: 'job.completed', jobId: job.id, receipt: recorded }); }
256
257
  return recorded;
@@ -379,7 +380,8 @@ export function createCommandBus({ registry, ports }) {
379
380
  throw error;
380
381
  }
381
382
  }
382
- return { run,
383
+ // noteUndone: edit:undone for the user's own undo (domains/scene-undo.js), which reaches it through the bus.
384
+ return { run, noteUndone,
383
385
  // Trusted UI adapter only: wire callers can consume, never mint a token.
384
386
  confirm(id, args = {}) { const prepared = registry.prepare(id, args), token = crypto.randomUUID(); confirmations.set(token, { id, args: prepared.args, host: ports.read().host, expires: (ports.now ?? Date.now)() + 300_000 }); return token; },
385
387
  subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
@@ -18,7 +18,9 @@ import { fitOutput, reportPage } from "../motion3/report.js";
18
18
  import { keyObject } from "../motion3/key-edit.js";
19
19
  import { expandUse } from "../motion3/skills/index.js";
20
20
  import { publishDraft } from "../agent-progress.js";
21
- import { qaSay } from "../qa-label.js";
21
+ import { qaProblems, qaSay } from "../qa-label.js";
22
+ import { noteTurnDraft } from "../workflow/agent-turn-telemetry.js";
23
+ import { noteDraftCompiled } from "../motion-draft-telemetry.js";
22
24
  import { carryEdit } from "../motion3/edit-carry.js";
23
25
  import { normalizeCompileArgs } from "../motion3/lenient.js";
24
26
  import { createCompileRunner } from "./motion3-compile.js";
@@ -181,7 +183,10 @@ export function register(registry, ports) {
181
183
  : best ? `; not installed; the best take so far, ${best.specId}, installed` : install === "ifClean" ? (installs ? "; installed" : "; not installed") : "";
182
184
  const output = report(r, { frames: r.frameCount, fps: TIMELINE_FPS, installed: Boolean(wanted) || self, ...(stuck ? { stuck } : {}), ...adjustedOf(notes) }, { ...delta, ...(r.repair ? { repair: r.repair } : {}), ...(timing ? { timing } : {}) });
183
185
  // agent-progress.js: viewport ghost, timeline beats, agent panel
184
- publishDraft(characterId, { take, installed: installs || kept || self, specId: output.specId, label: r.label, qa, timeline: r.timeline });
186
+ const draft = publishDraft(characterId, { take, installed: installs || kept || self, specId: output.specId, label: r.label, qa, timeline: r.timeline });
187
+ noteDraftCompiled(draft, r, { installed: installs || kept || self, stuck, repaired: Boolean(r.repair), adjusted: notes.length > 0 });
188
+ // agent:turn_summary: this turn's drafts and their QA (agent-turn-telemetry.js)
189
+ noteTurnDraft(context?.turnId, { clean: Boolean(qa.ok), problems: qaProblems(qa), stuck: Boolean(stuck) });
185
190
  return { affectedIds: installs || best ? [characterId] : [], summary: `Compiled ${r.frameCount} frames; QA ${qaSay(qa)}${how}${adjustedSay(notes)}.`, output, ...workerWarning() };
186
191
  });
187
192
  } });
package/src/controls.jsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import { useEffect, useRef } from "react";
2
2
  import { useFrame, useThree } from "@react-three/fiber";
3
3
  import * as THREE from "three";
4
+ import { noteCameraGesture } from "./thrash-friction.js";
4
5
 
5
6
  const MOVE_SPEED = 2.6; // metres per second
6
7
  const CRANE_SPEED = 1.3; // Q/E up/down runs at half walk speed — fine
@@ -162,13 +163,13 @@ export function FlyControls({ enabled, cameraLocked = false, camRef, look, getPi
162
163
  gesture.current = null;
163
164
  if (typeof window !== "undefined") window.__cozyclayCameraGesture = false;
164
165
  releaseNavLock();
165
- flushInvalidate();
166
166
  keys.current.clear();
167
167
  // the fly speed set with the wheel persists between flights, as it does in Unity
168
168
  element.style.cursor = "";
169
169
  flyStateRef.current?.(false);
170
170
  flushInvalidate();
171
- if (active.changed) cameraChangeRef.current?.();
171
+ // A gesture that moved the view counts toward camera:thrash (thrash-friction.js).
172
+ if (active.changed) { cameraChangeRef.current?.(); noteCameraGesture(active.kind); }
172
173
  };
173
174
 
174
175
  const onLostCapture = (e) => {
@@ -0,0 +1,45 @@
1
+ // app:render_crash and app:gl_lost: a white screen and a dead GPU context become
2
+ // countable and joinable to device:profile. Only closed values leave: the thrown
3
+ // value's type label (the app:error vocabulary, via describeError) and the GL
4
+ // failure kind. Never a message, stack, component stack or file name.
5
+ import { describeError, initAnalytics, track } from "./analytics.js";
6
+ import { admit, bump } from "./analytics-friction.js";
7
+
8
+ const CRASHES_PER_SESSION = 2;
9
+ const GL_LOST_KINDS = new Set(["unavailable", "context_lost"]);
10
+
11
+ // A crash on the first render, or a missing WebGL at mount, comes before the
12
+ // analytics SDK has loaded; initAnalytics() is idempotent (main.jsx already
13
+ // started it), so waiting on it keeps those events instead of dropping them.
14
+ let send = (event, props) => {
15
+ initAnalytics().then(() => track(event, props), () => {});
16
+ };
17
+
18
+ /** An error ErrorBoundary caught. React 19 does not re-dispatch a caught
19
+ * render error to window "error", so app:error never sees it and the friction
20
+ * `errors` counter moves here, not twice. */
21
+ export function reportRenderCrash(error) {
22
+ try {
23
+ bump("errors");
24
+ const props = { error_type: describeError({ error }).error_type };
25
+ if (admit("app:render_crash", CRASHES_PER_SESSION)) send("app:render_crash", props);
26
+ } catch {
27
+ // Telemetry must never throw from inside the crash net.
28
+ }
29
+ }
30
+
31
+ /** The stage's WebGL failed: "unavailable" at mount, "context_lost" later. Once per kind per session. */
32
+ export function reportGlLost(kind) {
33
+ try {
34
+ if (GL_LOST_KINDS.has(kind) && admit(`app:gl_lost:${kind}`, 1)) send("app:gl_lost", { kind });
35
+ } catch {
36
+ // Telemetry must never affect the stage.
37
+ }
38
+ }
39
+
40
+ /** Tests only: capture what is sent; returns the restore. */
41
+ export function crashTelemetrySeam(capture) {
42
+ const previous = send;
43
+ send = capture;
44
+ return () => { send = previous; };
45
+ }
@@ -2,6 +2,7 @@ import { copyPhysicsKeys } from "../motion/physics-review.js";
2
2
  import { useState, useMemo, useEffect, useSyncExternalStore, useContext } from "react";
3
3
  import { AppContext } from '../app-context.js';
4
4
  import { createDocumentStore } from "../document-store.js";
5
+ import { createSceneUndo } from "./scene-undo.js";
5
6
  import { useDocumentDomain } from "../store/use-document-store.js";
6
7
  import { arrangement } from "../studio-agent-commands.js";
7
8
  import { timelineContentExtent, timelineSpan } from '../timeline-extent.js';
@@ -713,17 +714,7 @@ export function useCast(appContext) {
713
714
  appContext.shared.bufferRef.current = { ...appContext.shared.bufferRef.current, waypoints: layer.waypoints };
714
715
  setWaypoints(layer.waypoints);
715
716
  }
716
- function undoScene() {
717
- const receipt = appContext.bus.run('edit.undo');
718
- // A refusal says why: the last edit belongs to a running task (parallel tasks), which its own card undoes.
719
- if (receipt.status === 'noop' || receipt.ok === false) appContext.notify(receipt.ok === false ? ko(receipt.message ?? "Undo was refused", `실행 취소 불가: ${receipt.message ?? ""}`) : ko("Nothing to undo", "실행 취소할 작업이 없어요"));
720
- return receipt;
721
- }
722
- function redoScene() {
723
- const receipt = appContext.bus.run('edit.redo');
724
- if (receipt.status === 'noop') appContext.notify(ko("Nothing to redo", "다시 실행할 작업이 없어요"));
725
- return receipt;
726
- }
717
+ const { undoScene, redoScene } = createSceneUndo(appContext);
727
718
  function snapshotStudioDomain(domain, targetId) {
728
719
  if (domain === 'motion' && appContext.storeDomain('motion')) return appContext.storeDomain('motion').snapshotTarget(targetId);
729
720
  const state = appContext.shared.readStudioState();
@@ -88,10 +88,8 @@ export function createMotionDomain(appContext, characters) {
88
88
  }
89
89
  return decoded.get(take);
90
90
  }
91
- const motionFor = id => materialize(layer(id).take), fullMotionFor = id => materialize(layer(id).fullTake);
92
- const visibleMotion = motionFor;
93
- const frame = () => appContext.live.state?.timeline.currentFrame ?? 0;
94
- const rigFor = id => appContext.shared.rigs[id];
91
+ const motionFor = id => materialize(layer(id).take), fullMotionFor = id => materialize(layer(id).fullTake), visibleMotion = motionFor;
92
+ const frame = () => appContext.live.state?.timeline.currentFrame ?? 0, rigFor = id => appContext.shared.rigs[id];
95
93
  // Rig-only tools refuse a capsule figure by name before looking for its rig.
96
94
  const rigOnly = (id, feature) => refuseRigOnly(appContext.storeDomain('cast')?.read().find(row => row.id === id), feature);
97
95
  function rigSnapshots() {
@@ -127,7 +125,8 @@ export function createMotionDomain(appContext, characters) {
127
125
  }
128
126
  publishedIds = new Set(read().map(row => row.id));
129
127
  const id = appContext.shared.loadedLayerCharRef.current;
130
- appContext.shared.ikStateRef.current = states.get(id) ?? createIkState();
128
+ // A character without a motion row keeps its live IK state in the map, so its first drag bakes.
129
+ appContext.shared.ikStateRef.current = states.get(id) ?? states.set(id, createIkState()).get(id);
131
130
  appContext.shared.bufferRef.current = { ...appContext.shared.bufferRef.current, motion: visibleMotion(id), ik: appContext.shared.ikStateRef.current };
132
131
  domain.onProject?.(); viewRevision++;
133
132
  }
@@ -233,7 +232,10 @@ export function createMotionDomain(appContext, characters) {
233
232
  writeLayer(id, { take: null, fullTake: null, ikKeys: [], ikPins: [], ikPinResiduals: [], committedIkEdits: [] });
234
233
  synchronizeTimeline();
235
234
  }
236
- function bakeCurrentKey(id, at, dragIds = null) {
235
+ // `preimage` is the rig before a drag: by drag end the rig already shows the drag, so the
236
+ // image the action records for Undo would otherwise be the dragged pose.
237
+ function bakeCurrentKey(id, at, dragIds = null, preimage = null) { const before = read(), receipt = bakeKey(id, at, dragIds); if (receipt?.ok && read() !== before && preimage) rigImages.get(before)?.set(id, preimage); return receipt; }
238
+ function bakeKey(id, at, dragIds) {
237
239
  const rig = rigFor(id), resolved = rig && resolveIkRig(rig);
238
240
  if (!resolved) return null;
239
241
  const take = motionFor(id);
@@ -244,7 +246,8 @@ export function createMotionDomain(appContext, characters) {
244
246
  if (keyed && take) for (const key of keyed.values()) key.blend = 6;
245
247
  return keyed ? run('ik.setKey', { characterId: id, frame: at, tracks: ikKeyJson(keyed) }) : null;
246
248
  }
247
- const scratch = { ...createIkState(), tracked: new Set(appContext.shared.ikStatesRef.current.get(id)?.tracked) };
249
+ // The loaded character's tracks are on the live slot, as in ikStateFor.
250
+ const scratch = { ...createIkState(), tracked: new Set((id === appContext.shared.loadedLayerCharRef.current ? appContext.shared.ikStateRef.current : appContext.shared.ikStatesRef.current.get(id))?.tracked) };
248
251
  ikBakeKeyframe(resolved.chains, scratch, at, resolved.fkJoints);
249
252
  const keyed = encodeMotionKeys(scratch.keys)[0];
250
253
  return keyed ? run('ik.setKey', { characterId: id, frame: at, tracks: keyed.tracks }) : null;
@@ -321,7 +324,7 @@ export function useMotion(appContext) {
321
324
  useSyncExternalStore(domain.documentStore.subscribe, domain.viewRevision, domain.viewRevision);
322
325
  useEffect(() => {
323
326
  domain.switchLayer(appContext.shared.activeChar.id);
324
- const start = () => domain.beginGesture(); window.addEventListener('pointerdown', start, true);
327
+ const start = () => { if (ikDragRef.current?.characterId === null) ikDragRef.current = null; domain.beginGesture(); }; window.addEventListener('pointerdown', start, true);
325
328
  return () => { window.removeEventListener('pointerdown', start, true); domain.finishGesture(true); };
326
329
  }, [domain, appContext.shared.activeChar.id]);
327
330
  // IK posing for Subject 1: dragging a wrist/ankle handle FOCUSES that
@@ -395,7 +398,7 @@ export function useMotion(appContext) {
395
398
 
396
399
  function restorePendingIkState(pending) {
397
400
  // A replaced take or another authored edit owns the newer state.
398
- if (domain.layer(pending.characterId) !== pending.sourceLayer) return;
401
+ if (domain.layer(pending.characterId) !== pending.sourceLayer) return false;
399
402
  const state = pending.state;
400
403
  state.keys = copyPhysicsKeys(pending.beforeKeys);
401
404
  state.tracked = new Set(pending.beforeTracked);
@@ -406,23 +409,24 @@ export function useMotion(appContext) {
406
409
  else appContext.shared.poseMemberAtFrame(pending.rig, pending.motion, state, appContext.shared.tlFrame, IK_CORRECTION_BLEND_FRAMES);
407
410
  if (state.chains) ikSeedTargets(state.chains, state);
408
411
  }
412
+ return true;
409
413
  }
410
414
 
415
+ // true when the preview was backed out; a preview an authored edit made stale is dropped without restoring anything
411
416
  function cancelPendingIkEdit() {
412
417
  const pending = pendingIkEditRef.current;
413
418
  if (!pending) return false;
414
- restorePendingIkState(pending);
419
+ const restored = restorePendingIkState(pending);
415
420
  setPendingIkEditValue(null);
416
- ikDragRef.current = null;
417
- ikPreDragRef.current = null;
421
+ ikDragRef.current = ikPreDragRef.current = null;
418
422
  setIkTick((value) => value + 1);
419
- return true;
423
+ return restored;
420
424
  }
421
425
 
422
426
  function applyPendingIkEdit() {
423
427
  const pending = pendingIkEditRef.current;
424
428
  if (!pending) return false;
425
- if (pending.characterId !== appContext.shared.activeChar.id || domain.layer(pending.characterId) !== pending.sourceLayer) {
429
+ if (domain.layer(pending.characterId) !== pending.sourceLayer) {
426
430
  cancelPendingIkEdit();
427
431
  return false;
428
432
  }
@@ -435,13 +439,13 @@ export function useMotion(appContext) {
435
439
  throw error;
436
440
  }
437
441
  setPendingIkEditValue(null);
438
- ikDragRef.current = null;
439
- ikPreDragRef.current = null;
440
- if (pending.rig) appContext.shared.poseMemberAtFrame(pending.rig, motion, pending.state, appContext.shared.tlFrame, IK_CORRECTION_BLEND_FRAMES);
442
+ ikDragRef.current = ikPreDragRef.current = null;
443
+ if (pending.rig) appContext.shared.poseMemberAtFrame(pending.rig, pending.motion, pending.state, appContext.shared.tlFrame, IK_CORRECTION_BLEND_FRAMES);
441
444
  setIkTick((value) => value + 1);
442
- appContext.notify(ko(`Applied IK correction across frames ${pending.startFrame}–${pending.endFrame}`,
443
- `IK 보정을 ${pending.startFrame}–${pending.endFrame}프레임에 적용했어요`,
444
- `已在第 ${pending.startFrame}–${pending.endFrame} 帧应用 IK 修正`));
445
+ // Applied on a selection switch: name the character (its Outliner label) the edit landed on.
446
+ const owner = pending.characterId !== appContext.shared.activeChar.id && appContext.shared.characters.findIndex(entry => entry.id === pending.characterId) + 1;
447
+ appContext.notify(owner ? ko(`Applied Character ${owner}'s IK edit`, `인물 ${owner}의 IK 보정을 적용했어요`, `已应用角色 ${owner} 的 IK 修正`)
448
+ : ko(`Applied IK correction across frames ${pending.startFrame}–${pending.endFrame}`, `IK 보정을 ${pending.startFrame}–${pending.endFrame}프레임에 적용했어요`, `已在第 ${pending.startFrame}–${pending.endFrame} 帧应用 IK 修正`));
445
449
  return true;
446
450
  }
447
451
 
@@ -593,11 +597,12 @@ export function useMotion(appContext) {
593
597
  // Loaded motion: decoded arrays plus the world anchor captured at load.
594
598
  const motion = domain.visibleMotion(appContext.shared.activeChar.id);
595
599
  useEffect(() => {
596
- const pending = pendingIkEditRef.current;
597
- if (pending && (pending.characterId !== appContext.shared.activeChar.id
598
- || pending.rig !== appContext.shared.activeRig || pending.motion !== motion
599
- || pending.sourceLayer !== domain.layer(pending.characterId)
600
- || !ikMode || ikEditTool !== "ik")) cancelPendingIkEdit();
600
+ if (ikDragRef.current && ikDragRef.current.characterId !== appContext.shared.activeChar.id) abortIkDrag(true);
601
+ const pending = pendingIkEditRef.current, id = pending?.characterId, other = id !== appContext.shared.activeChar.id;
602
+ const current = pending && pending.rig === appContext.shared.rigs[id] && pending.motion === domain.visibleMotion(id) && pending.sourceLayer === domain.layer(id) && ikMode && ikEditTool === "ik";
603
+ // Selecting another character applies a still-current preview, as leaving Pose mode does.
604
+ if (current && other) applyPendingIkEdit();
605
+ else if (pending && (!current || other || pending.rig !== appContext.shared.activeRig || pending.motion !== motion)) cancelPendingIkEdit();
601
606
  }, [appContext.shared.activeChar.id, appContext.shared.activeRig, motion, pinLayer, ikMode, ikEditTool]);
602
607
  const rangePinRebuildRef = useRef(null);
603
608
  const rangePinSourceStamp = JSON.stringify([pinLayer.take, appContext.shared.activeChar.id]);
@@ -737,6 +742,7 @@ export function useMotion(appContext) {
737
742
  // ends pinned (the handle snaps to the clamped position); FK joints swing
738
743
  // toward the pointer. The solved pose stays a preview until Apply.
739
744
  function ikSolve(kind, trackId, targetWorld) {
745
+ if (ikDragRef.current && ikDragRef.current.characterId !== appContext.shared.activeChar.id) return;
740
746
  const state = appContext.shared.ikStateRef.current;
741
747
  const ikChains = state.chains;
742
748
  const ikFkJoints = state.fkJoints;
@@ -755,7 +761,7 @@ export function useMotion(appContext) {
755
761
  };
756
762
  ikDragRef.current = { frame: appContext.shared.tlFrame, ids: new Set(pending?.ids ?? []) };
757
763
  }
758
- ikDragRef.current = ikDragRecord(ikDragRef.current, appContext.shared.tlFrame);
764
+ ikDragRef.current = Object.assign(ikDragRecord(ikDragRef.current, appContext.shared.tlFrame), { characterId: appContext.shared.activeChar.id });
759
765
  const touch = (id) => ikDragTouch(appContext.shared.ikStateRef.current, ikDragRef.current, id);
760
766
  if (kind === "chain") {
761
767
  const chain = appContext.shared.ikStateRef.current.chains?.get(trackId);
@@ -822,29 +828,34 @@ export function useMotion(appContext) {
822
828
  solveSwingAngle(joint, targetWorld.axis, targetWorld.angle, targetWorld.startQuat, targetWorld.startParentQuat);
823
829
  }
824
830
 
831
+ // A drag belongs to the character it started on. Switching away mid-drag
832
+ // restores that rig and leaves an inert record (no owner) so the rest of
833
+ // the stroke cannot pose the newly selected character.
834
+ function abortIkDrag(inert = false) {
835
+ if (ikPreDragRef.current?.beforeRig) appContext.shared.restoreExportRig(ikPreDragRef.current.beforeRig);
836
+ ikDragRef.current = inert ? { characterId: null, frame: null, ids: new Set() } : null;
837
+ ikPreDragRef.current = null;
838
+ appContext.shared.ikBodyDragRef.current = false;
839
+ }
840
+
825
841
  // Drag end: retain the solved pose as a preview. Apply creates keys at both
826
842
  // boundaries of the selected timeline motion segment.
827
843
  function ikDragEnd() {
828
844
  appContext.shared.ikBodyDragRef.current = false;
829
- const drag = ikDragRef.current;
845
+ const drag = ikDragRef.current, pre = ikPreDragRef.current;
846
+ if (drag && drag.characterId !== appContext.shared.activeChar.id) return abortIkDrag();
830
847
  ikDragRef.current = null;
831
848
  if (!motion) {
832
- keyIkPoseAtPlayhead();
849
+ keyIkPoseAtPlayhead(null, pre?.characterId === appContext.shared.activeChar.id ? pre.beforeRig : null);
833
850
  ikPreDragRef.current = null;
834
851
  setIkTick((n) => n + 1);
835
852
  return;
836
853
  }
837
- if (!drag?.ids?.size) {
838
- ikPreDragRef.current = null;
839
- return;
840
- }
854
+ if (!drag?.ids?.size) return void (ikPreDragRef.current = null);
841
855
  const state = appContext.shared.ikStateRef.current;
842
856
  const raw = (rawRig, at) => appContext.shared.poseMemberAtFrame(rawRig, motion, null, at);
843
857
  const keyed = bakeIkDragKey(state.chains, state.fkJoints, drag.frame, drag.ids, raw);
844
- if (!keyed) {
845
- ikPreDragRef.current = null;
846
- return;
847
- }
858
+ if (!keyed) return void (ikPreDragRef.current = null);
848
859
  const before = ikPreDragRef.current;
849
860
  const range = pendingIkEditRef.current ?? selectedIkRange(drag.frame);
850
861
  const next = copyPhysicsKeys(before.beforeKeys);
@@ -869,8 +880,8 @@ export function useMotion(appContext) {
869
880
  * and set them as a key through the shared registry. A bake only writes
870
881
  * TRACKED parts: with nothing dragged yet there is no key, nothing is
871
882
  * dispatched and Ctrl+Z never goes dead. */
872
- function keyIkPoseAtPlayhead(dragIds = null) {
873
- if (appContext.storeDomain('motion')) return appContext.storeDomain('motion').bakeCurrentKey(appContext.shared.activeChar.id, appContext.shared.tlFrame, dragIds);
883
+ function keyIkPoseAtPlayhead(dragIds = null, preimage = null) {
884
+ if (appContext.storeDomain('motion')) return appContext.storeDomain('motion').bakeCurrentKey(appContext.shared.activeChar.id, appContext.shared.tlFrame, dragIds, preimage);
874
885
  const scratch = { ...createIkState(), tracked: new Set(appContext.shared.ikStateRef.current.tracked) };
875
886
  ikBakeKeyframe(ikChains, scratch, appContext.shared.tlFrame, ikFkJoints);
876
887
  const baked = scratch.keys.get(appContext.shared.tlFrame);
@@ -3,6 +3,7 @@ import { useState, useRef } from "react";
3
3
  import { createDocumentStore } from "../document-store.js";
4
4
  import { useDocumentDomain } from "../store/use-document-store.js";
5
5
  import { arrangement } from "../studio-agent-commands.js";
6
+ import { noteObjectCreated, noteObjectDeleted } from "../studio-telemetry.js";
6
7
  import {
7
8
  readStoredObjectColors,
8
9
  rememberObjectColor,
@@ -243,6 +244,7 @@ export function useObjects(appContext) {
243
244
  if (!id) return;
244
245
  const wasSelected = id === selectedSceneObjectId;
245
246
  run("object.remove", { ids: [id] });
247
+ noteObjectDeleted(id);
246
248
  setObjectDeleteUndo({ id, pastDepth: store.depths().past });
247
249
  appContext.shared.setInspectorActionsOpen(false);
248
250
  if (wasSelected) {
@@ -306,6 +308,7 @@ export function useObjects(appContext) {
306
308
  : {});
307
309
  const receipt = run("object.add", { kind, placement, first: true });
308
310
  const object = domain.read().find(row => row.id === receipt.affectedIds[0]);
311
+ noteObjectCreated(object.id);
309
312
  appContext.shared.markCraftAction("object");
310
313
  appContext.shared.setSelectedHierarchyId(`object:${object.id}`);
311
314
  if (object.renderer === "empty") setRenameRequest({ id: `object:${object.id}`, nonce: Date.now() });
@@ -0,0 +1,27 @@
1
+ import { ko } from "../locale.js";
2
+
3
+ // The Studio's Ctrl+Z / Ctrl+Shift+Z and Edit menu: one bus step each, with the reason when nothing moves.
4
+ export function createSceneUndo(appContext) {
5
+ // `via`: the user's key, menu or button (edit:undone). The agent's undo_edit does not come through here.
6
+ function undoScene(via) {
7
+ // Through the bus (command-bus-telemetry.js): extracted App fixtures see only appContext here.
8
+ const note = receipt => { try { appContext.bus.noteUndone?.(via, receipt); } catch { /* telemetry is advisory */ } };
9
+ // An un-applied IK drag is a preview outside history: Ctrl+Z backs it out first.
10
+ if (appContext.shared.motionDomain?.cancelPendingIkEdit?.()) {
11
+ appContext.notify(ko("IK edit undone", "IK 수정을 되돌렸어요"));
12
+ note(null);
13
+ return { ok: true, status: 'done' };
14
+ }
15
+ const receipt = appContext.bus.run('edit.undo');
16
+ note(receipt);
17
+ // A refusal says why: the last edit belongs to a running task (parallel tasks), which its own card undoes.
18
+ if (receipt.status === 'noop' || receipt.ok === false) appContext.notify(receipt.ok === false ? ko(receipt.message ?? "Undo was refused", `실행 취소 불가: ${receipt.message ?? ""}`) : ko("Nothing to undo", "실행 취소할 작업이 없어요"));
19
+ return receipt;
20
+ }
21
+ function redoScene() {
22
+ const receipt = appContext.bus.run('edit.redo');
23
+ if (receipt.status === 'noop') appContext.notify(ko("Nothing to redo", "다시 실행할 작업이 없어요"));
24
+ return receipt;
25
+ }
26
+ return { undoScene, redoScene };
27
+ }
@@ -46,7 +46,7 @@ import { internWorkflowOutputs, workflowOutputRefs, resolveWorkflowOutputs } fro
46
46
 
47
47
  import { resourceManifest } from "../project-resources.js";
48
48
  import { ko } from "../locale.js";
49
- import { track, bucketCount, bucketProjectAge, startExportAttempt } from "../analytics.js";
49
+ import { track, bucketCount, bucketProjectAge } from "../analytics.js"; import { startExportAttempt } from "../export-attempt.js";
50
50
  import { mergeProjectCustomPoses } from "../project-poses.js";
51
51
  import { DEFAULT_WORKSPACE_LAYOUT, DEFAULT_DURATION_S, TIMELINE_FPS } from "../app-stage.jsx";
52
52
  import { saveCustomPoses } from "../poses.js";
@@ -1,5 +1,6 @@
1
1
  import { Component } from "react";
2
2
  import { ko } from "./locale.js";
3
+ import { reportRenderCrash } from "./crash-telemetry.js";
3
4
 
4
5
  /**
5
6
  * Last line of defense for the whole tree. A render-time throw anywhere in
@@ -23,6 +24,7 @@ export default class ErrorBoundary extends Component {
23
24
 
24
25
  componentDidCatch(error, info) {
25
26
  console.error("[cozyclay] render crash", error, info?.componentStack ?? "");
27
+ reportRenderCrash(error);
26
28
  }
27
29
 
28
30
  render() {
@@ -0,0 +1,100 @@
1
+ import { bucketCount, bucketMs, exportFailureCode, sanitizeProps, track } from "./analytics.js";
2
+
3
+ // Retry re-runs the identical frozen export request, so a request seen before
4
+ // is a retry of the attempt it last started. Weak: requests are never kept.
5
+ const lastAttemptOf = new WeakMap();
6
+ const PROGRESS_STAGES = new Set(["preparing", "encoding", "finalizing"]);
7
+
8
+ /** Completed frames of the counted step as a closed percent bucket. */
9
+ function bucketProgress(done, total) {
10
+ if (!(total > 0) || !(done > 0)) return "0";
11
+ const percent = (done / total) * 100;
12
+ if (percent <= 25) return "1-25";
13
+ if (percent <= 50) return "26-50";
14
+ if (percent <= 75) return "51-75";
15
+ return "76-99";
16
+ }
17
+
18
+ /**
19
+ * One user-initiated export, ending at pipeline completion/download handoff.
20
+ * Optional { now, capture } dependencies keep fixtures deterministic. Telemetry
21
+ * failures (including unavailable randomness) must not change export behavior.
22
+ * `metadata.request` (never sent) identifies a retried request; a numeric
23
+ * `metadata.objects` is sent as its count bucket.
24
+ */
25
+ export function startExportAttempt(metadata, dependencies = {}) {
26
+ let terminal = false;
27
+ let props = null;
28
+ let startedAt = NaN;
29
+ let stage = "preparing";
30
+ let progress = "0";
31
+ let now = () => performance.now();
32
+ let capture = track;
33
+ const readClock = () => {
34
+ try { return now(); } catch { return NaN; }
35
+ };
36
+ const emit = (event, payload) => {
37
+ try {
38
+ Promise.resolve(capture(event, sanitizeProps(event, payload))).catch(() => {
39
+ // A rejected transport is as non-fatal as a synchronous failure.
40
+ });
41
+ } catch {
42
+ // Analytics must never affect the export or its error handling.
43
+ }
44
+ };
45
+ try {
46
+ now = dependencies.now ?? now;
47
+ capture = dependencies.capture ?? capture;
48
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
49
+ const attempt_id = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
50
+ const { request, objects, ...descriptor } = metadata ?? {};
51
+ const keyed = request !== null && typeof request === "object";
52
+ const retryOf = keyed ? lastAttemptOf.get(request) : undefined;
53
+ props = {
54
+ ...sanitizeProps("export:attempt_started", descriptor),
55
+ attempt_id,
56
+ is_retry: Boolean(retryOf),
57
+ ...(retryOf ? { retry_of: retryOf } : {}),
58
+ ...(Number.isFinite(objects) ? { objects: bucketCount(objects) } : {}),
59
+ };
60
+ if (keyed) lastAttemptOf.set(request, attempt_id);
61
+ startedAt = readClock();
62
+ emit("export:attempt_started", props);
63
+ } catch {
64
+ // Without a secure random ID, omit the attempt rather than inventing
65
+ // a persistent/content-derived identifier or blocking the export.
66
+ props = null;
67
+ }
68
+ const finish = (result, error, fallbackCode, handedOff) => {
69
+ if (terminal) return;
70
+ terminal = true;
71
+ if (!props) return;
72
+ try {
73
+ const payload = { ...props, duration_bucket: bucketMs(readClock() - startedAt) };
74
+ if (result === "failed") {
75
+ payload.failure_code = exportFailureCode(error, fallbackCode);
76
+ if (payload.failure_code === "aborted") result = "cancelled";
77
+ // A file already handed to the browser or folder ends the run in handoff.
78
+ payload.stage = handedOff > 0 ? "handoff" : stage;
79
+ payload.progress = progress;
80
+ }
81
+ emit(`export:attempt_${result}`, payload);
82
+ } catch {
83
+ // Clock/payload failures are isolated from the actual export too.
84
+ }
85
+ };
86
+ return {
87
+ /** The export's own status update: { phase, stage?, completedFrames?, frameCount? }. */
88
+ note(phase, details = {}) {
89
+ try {
90
+ if (terminal || !PROGRESS_STAGES.has(phase)) return;
91
+ stage = phase === "finalizing" && details.stage === "download" ? "handoff" : phase;
92
+ if (Number.isFinite(details.frameCount)) progress = bucketProgress(details.completedFrames, details.frameCount);
93
+ } catch {
94
+ // Progress bookkeeping is advisory like the rest of the lifecycle.
95
+ }
96
+ },
97
+ succeed() { finish("succeeded"); },
98
+ fail(error, fallbackCode = "unknown", handedOff = 0) { finish("failed", error, fallbackCode, handedOff); },
99
+ };
100
+ }
@@ -1,6 +1,7 @@
1
1
  // Optional export folder. When the browser grants a directory, download-type
2
2
  // exports are written there; every failure path falls back to the browser's
3
3
  // normal download so an export is never lost.
4
+ import { track } from "./analytics.js";
4
5
 
5
6
  const DB_NAME = "cozyclay-export-workspace";
6
7
  const DB_VERSION = 1;
@@ -211,8 +212,18 @@ export async function clearExportWorkspace() {
211
212
  }
212
213
  }
213
214
 
214
- /** Save an export to the chosen folder, or hand it to the browser on any miss. */
215
+ // saveExport's fallback reasons as the closed export:saved vocabulary.
216
+ const SAVED_REASONS = { "unsupported": "unsupported", "no-workspace": "no_workspace", "workspace-permission": "permission", "workspace-write-failed": "write_failed" };
217
+
218
+ /** Save an export to the chosen folder, or hand it to the browser on any miss.
219
+ * Every call reports export:saved (method and fallback reason, never a name). */
215
220
  export async function saveExport(source, name, options = {}) {
221
+ const result = await saveExportFile(source, name, options);
222
+ (options.track ?? track)("export:saved", { method: result.method, reason: SAVED_REASONS[result.reason] ?? "none" });
223
+ return result;
224
+ }
225
+
226
+ async function saveExportFile(source, name, options) {
216
227
  const injectedDirectory = Object.prototype.hasOwnProperty.call(options, "directory");
217
228
  const download = options.download ?? clickDownload;
218
229
  if (!injectedDirectory && !canChooseExportWorkspace()) {