@widgetic/creator 0.4.0 → 0.4.2

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.
@@ -166,6 +166,16 @@
166
166
  import { pinScrollToBottom } from './utils/pinScrollToBottom.js';
167
167
  import { installFreezeWatchdog, measureSync } from './utils/freezeWatchdog.js';
168
168
  import { streamOperationUpdates } from './utils/operationStream.js';
169
+ import {
170
+ httpStatusOfFailure,
171
+ isFinishedOperationStatus,
172
+ isGenerationOfWidget,
173
+ openGenerationChannel,
174
+ readOperationBody,
175
+ requestOperationStop,
176
+ type GenerationChannel,
177
+ type OperationSnapshot
178
+ } from './utils/generationSharing.js';
169
179
  import { generateEmbedCode, EMBED_FORMATS, type EmbedFormat } from './utils/embedCode.js';
170
180
 
171
181
  function openEmbedTestPage(href: string) {
@@ -1304,7 +1314,28 @@
1304
1314
  return /generating code|saving to repository/i.test(generateCodeStatus || '');
1305
1315
  }
1306
1316
  const widgetAbortControllers = new Map<string, AbortController>();
1317
+ /**
1318
+ * The runs Stop was pressed in. A run that is still waiting for the server to name its job (the request that starts it is
1319
+ * on its way) has nothing yet to cancel: it cancels the job as soon as the server names it.
1320
+ */
1321
+ const abortControllersStoppedByUser = new WeakSet<AbortController>();
1307
1322
  let currentGenerationOperationId: string | null = null;
1323
+ /**
1324
+ * The operation each widget's running generation is, from the moment the server named it until it ends: what Stop cancels
1325
+ * on the server, and what this tab tells the other tabs of the browser (or answers when they ask). A generation this tab
1326
+ * only follows, because another tab began it, is in here too, so Stop pressed in either tab stops the same job.
1327
+ */
1328
+ const generationOperationByWidgetId = new Map<string, string>();
1329
+ /** The widgets whose generation this tab follows rather than runs: a creator that closes lets go of their streams. */
1330
+ const followedGenerationWidgetIds = new Set<string>();
1331
+ /** The widgets this tab is just now checking the server about, so one operation is taken on once however many tabs announce it. */
1332
+ const widgetsBeingJoined = new Set<string>();
1333
+ /** The widgets this tab asked the other tabs about already: showing a widget asks once, and an announcement covers the rest. */
1334
+ const widgetsAskedAboutGeneration = new Set<string>();
1335
+ /** This tab's end of the channel the tabs of a browser use to tell each other about a generation (null where the browser has none). */
1336
+ let generationChannel: GenerationChannel | null = null;
1337
+ /** True once this tab has opened its end of the channel (or found the browser has none): from then on it asks about the widgets it shows. */
1338
+ let generationSharingReady = false;
1308
1339
  let generateCodeStatus: string | null = null;
1309
1340
  let lastGenerationFailed = false; // Track if last generation failed for retry UI
1310
1341
  let publishPlanMessageByWidgetId: Record<string, string> = {};
@@ -3234,7 +3265,6 @@
3234
3265
  && !!lastCommitId
3235
3266
  && lastPublishedVersion === null;
3236
3267
 
3237
- let codeGenerationAbortController: AbortController | null = null;
3238
3268
  let isCheckingActiveGeneration = false; // Set synchronously to block auto-open preview during async check
3239
3269
 
3240
3270
  /** Controls which tab is active in the inline Preview & Console panel: 'preview' | 'console' | null (collapsed) */
@@ -5741,7 +5771,8 @@
5741
5771
  if (!event.key) return;
5742
5772
 
5743
5773
  if (event.key === `crossTab_generating_${selectedWidgetId}`) {
5744
- isGeneratingInOtherTab = event.newValue !== null && !isGeneratingCode;
5774
+ // Not while this tab follows that generation itself (see `followGeneration`): it shows it as running here
5775
+ isGeneratingInOtherTab = event.newValue !== null && !isGeneratingCode && !(selectedWidgetId && generatingWidgetIds[selectedWidgetId]);
5745
5776
  // console.log('[CrossTab] Generation state changed from other tab:', isGeneratingInOtherTab);
5746
5777
  }
5747
5778
 
@@ -5791,187 +5822,333 @@
5791
5822
  } catch (e) { return null; }
5792
5823
  }
5793
5824
 
5825
+ // ─── A generation this tab did not start ───
5826
+ //
5827
+ // A generation runs on the server, so any tab of the visitor can follow it by the operation's status, whichever tab started
5828
+ // it. The tab that starts one tells the others (`generationChannel`), a tab that shows the widget later asks, and a browser
5829
+ // that kept the operation's id for the widget (the tab was refreshed) has it to look up. What the server says is the state:
5830
+ // a tab does not believe a flag that a closed tab could have left behind.
5831
+
5832
+ /** Why a tab follows a generation it did not start in this very run. */
5833
+ type GenerationFollowOrigin =
5834
+ /** Another tab said it had started one. */
5835
+ | 'announced'
5836
+ /** This browser kept the operation's id for the widget (the tab was refreshed, or opened after another began it). */
5837
+ | 'stored'
5838
+ /** This tab's own Stop came after the job had ended: shows how it ended. */
5839
+ | 'stop-too-late'
5840
+ /** This tab's own Stop could not reach the server: the job may still be running. */
5841
+ | 'stop-failed';
5842
+
5843
+ /** Forgets the id this browser kept for the widget, when it is this operation's (the id of a newer generation stays). */
5844
+ async function forgetStoredOperationId(widgetId: string, operationId: string): Promise<void> {
5845
+ try {
5846
+ if ((await getStoredOperationId(widgetId)) === operationId) clearActiveOperationId(widgetId);
5847
+ } catch (error) {
5848
+ console.warn('[GenerationSharing] Could not forget the operation kept for the widget', { widgetId, operationId, error });
5849
+ }
5850
+ }
5851
+
5794
5852
  /**
5795
- * Check if there's an active generation for the current widget and resume polling.
5796
- * Called after widget is selected/restored (e.g. after browser refresh).
5797
- * Strategy:
5798
- * 1. Check the durable store for a stored operationId
5799
- * 2. If found, poll its status — if still running, resume the "generating" UI
5853
+ * Follows a generation this tab did not start: the widget shows as generating here, with its progress, until the server says
5854
+ * the operation ended, and then shows how it ended. The server is asked first, so an id that is not this visitor's, or whose
5855
+ * operation ended long ago, changes nothing. Safe to call again for the same operation: a widget that already generates in
5856
+ * this tab (run here, or followed already) is left alone.
5800
5857
  */
5801
- async function checkAndResumeActiveGeneration() {
5802
- if (!selectedWidgetId || isGeneratingCode) return;
5858
+ async function followGeneration(widgetId: string, operationId: string, origin: GenerationFollowOrigin): Promise<void> {
5859
+ const client = operationsClient;
5860
+ if (!client || !getWidgetById(widgetId)) return;
5861
+ if (generatingWidgetIds[widgetId] || widgetAbortControllers.has(widgetId) || widgetsBeingJoined.has(widgetId)) return;
5862
+ widgetsBeingJoined.add(widgetId);
5803
5863
 
5804
- const resumeWidgetId = selectedWidgetId;
5805
- isCheckingActiveGeneration = true;
5806
-
5807
- // Check durable store for a stored operationId
5808
- let operationId = await getStoredOperationId();
5809
- let source = 'durable-cache';
5864
+ try {
5865
+ let snapshot: OperationSnapshot | null = null;
5866
+ try {
5867
+ const answer = await client.operationsIdGetRaw({ id: operationId });
5868
+ snapshot = readOperationBody(await answer.raw.json());
5869
+ } catch (error) {
5870
+ const httpStatus = httpStatusOfFailure(error);
5871
+ if (httpStatus === 404 || httpStatus === 403) {
5872
+ // The server has no such operation for this visitor (it expired, or it is another visitor's): nothing to follow
5873
+ if (origin === 'stored') void forgetStoredOperationId(widgetId, operationId);
5874
+ } else {
5875
+ console.warn('[GenerationSharing] Could not ask the server about the operation', { widgetId, operationId, origin, error });
5876
+ }
5877
+ return;
5878
+ }
5810
5879
 
5811
- if (!operationId) {
5812
- isCheckingActiveGeneration = false;
5813
- // No active generation found — clear stale cross-tab flags
5814
- if (isGeneratingInOtherTab) {
5815
- isGeneratingInOtherTab = false;
5816
- setCrossTabGenerating(false);
5817
- // console.log('[CrossTab] Cleared stale generating flag — no active generation on backend');
5880
+ // While the server was asked, this tab may have started a generation of its own on the widget
5881
+ if (generatingWidgetIds[widgetId] || widgetAbortControllers.has(widgetId)) return;
5882
+ if (!snapshot || !isGenerationOfWidget(snapshot, widgetId)) {
5883
+ if (snapshot && origin === 'stored') void forgetStoredOperationId(widgetId, operationId);
5884
+ return;
5818
5885
  }
5819
- return;
5820
- }
5821
5886
 
5822
- currentGenerationOperationId = operationId;
5823
- // console.log(`[GenerationResilience] Found active generation from ${source}: operationId=${operationId}`);
5887
+ if (isFinishedOperationStatus(snapshot.status)) {
5888
+ // It ended before this tab asked (the tab was away, or the stop came too late): show how it ended. A stop that
5889
+ // did go through, whose answer was lost on the way, is on the screen already.
5890
+ if (origin === 'stop-failed' && snapshot.status === 'cancelled') return;
5891
+ await finishFollowedGeneration(widgetId, operationId, snapshot, origin === 'stored' || origin === 'stop-too-late');
5892
+ return;
5893
+ }
5824
5894
 
5825
- // Step 3: Check operation status
5826
- try {
5827
- const op = (await operationsClient.operationsIdGet({ id: operationId })) as {
5828
- status?: string;
5829
- error?: string;
5830
- progress?: number;
5831
- metadata?: Record<string, unknown>;
5832
- };
5833
- const status = (op?.status || '').toLowerCase();
5834
-
5835
- if (status === 'completed') {
5836
- // console.log('[GenerationResilience] Generation already completed. Clearing stored ID.');
5837
- clearActiveOperationId();
5838
- isCheckingActiveGeneration = false;
5839
- hasChangesToSave = true;
5840
- const resumeCommitSha = getOperationCommitId(op?.metadata as Record<string, unknown> | undefined);
5841
- if (resumeCommitSha && resumeWidgetId) {
5842
- lastCommitId = resumeCommitSha;
5843
- saveCommitIdForWidget(resumeWidgetId, resumeCommitSha);
5844
- // console.log(`[Version] Commit restored from completed operation: ${resumeCommitSha.substring(0, 7)}`);
5845
- }
5846
- generateCodeStatus = 'Code generation completed! Auto-saving...';
5847
- showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5848
- description: $t('creator.codegen.generationFinishedWhileYouWere'),
5849
- duration: 5000
5895
+ // Take the generation on: from here the widget shows as generating in this tab, whoever started it
5896
+ const controller = new AbortController();
5897
+ const signal = controller.signal;
5898
+ widgetAbortControllers.set(widgetId, controller);
5899
+ followedGenerationWidgetIds.add(widgetId);
5900
+ generationOperationByWidgetId.set(widgetId, operationId);
5901
+ generatingWidgetIds = { ...generatingWidgetIds, [widgetId]: true };
5902
+ noteCodegenActive(true);
5903
+ let endedOperation: OperationSnapshot | null = null;
5904
+ try {
5905
+ screenshotGenerationEpoch += 1;
5906
+ abortScreenshotsInFlight();
5907
+ cancelQuietScreenshots();
5908
+ cancelIdleThumbnailPersist();
5909
+ widgetShapeLivePreviewsRef?.cancelReloads?.();
5910
+ if (widgetId === focusedPanelWidgetId) isGeneratingCode = true;
5911
+ if (widgetId === selectedWidgetId) isGeneratingInOtherTab = false;
5912
+ if (!currentGenerationOperationId) currentGenerationOperationId = operationId;
5913
+ patchCodegenUiState(widgetId, {
5914
+ lastGenerationFailed: false,
5915
+ lastGenerationError: null,
5916
+ generateCodeStatus: 'Code generation in progress...',
5850
5917
  });
5851
- generateCodeStatus = 'Code generation completed! Changes saved to GitLab.';
5852
- setTimeout(async () => {
5853
- if (selectedWidgetId !== resumeWidgetId) return;
5854
- widgetDetails?.setInlinePanelView('preview');
5855
- widgetDetails?.setHasAutoOpenedPreview(true);
5856
- await widgetDetails?.refreshPreview({ withRetry: true });
5857
- }, 1000);
5858
- return;
5859
- }
5860
-
5861
- if (status === 'failed' || status === 'cancelled') {
5862
- // console.log(`[GenerationResilience] Generation ${status}. Clearing stored ID.`);
5863
- clearActiveOperationId();
5864
- isCheckingActiveGeneration = false;
5865
- if (status === 'failed') {
5866
- const failedMsg = op?.error || 'Generation failed while you were away.';
5867
- const isServiceErr = failedMsg.includes('temporarily unavailable') || failedMsg.includes('Our team has been notified');
5868
- lastGenerationFailed = true;
5869
- lastGenerationError = failedMsg;
5870
- generateCodeStatus = `❌ Code generation failed`;
5871
- showToast('error', isServiceErr ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
5872
- description: failedMsg,
5873
- duration: isServiceErr ? 10000 : 6000
5918
+ pushCodegenProgressToUi(snapshot, widgetId);
5919
+ getWidgetDetailsRef(widgetId)?.setInlinePanelView('preview');
5920
+ getWidgetDetailsRef(widgetId)?.markCodegenStarted?.();
5921
+ // The prompt that began it is in the conversation on the server; this tab may not have loaded it yet
5922
+ void getChatMethodsForWidget(widgetId)?.reloadConversationMessages?.();
5923
+ // This tab learned of it from the browser's own store: the other tabs may not know of it yet
5924
+ if (origin === 'stored') generationChannel?.announceStarted(widgetId, operationId);
5925
+ if (widgetId === focusedPanelWidgetId && origin !== 'stop-failed') {
5926
+ showToast('info', $t('creator.codegen.generationInProgress'), {
5927
+ description: $t('creator.codegen.reconnectedToAnActiveCode'),
5928
+ duration: 4000
5874
5929
  });
5875
5930
  }
5876
- return;
5931
+
5932
+ const lastUpdate = await waitForOperation(
5933
+ operationId,
5934
+ (update) => {
5935
+ // The end is shown once, below, from what the wait settles with
5936
+ if (signal.aborted || !update || isFinishedOperationStatus(update.status)) return;
5937
+ pushCodegenProgressToUi(update, widgetId);
5938
+ },
5939
+ signal
5940
+ );
5941
+ endedOperation = readOperationBody(lastUpdate);
5942
+ } catch (error) {
5943
+ // A Stop pressed in this tab aborts the wait, and has shown it stopped already
5944
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
5945
+ console.warn('[GenerationSharing] Lost track of the generation this tab followed', { widgetId, operationId, error });
5946
+ const trackingLostText = 'Generation tracking lost.';
5947
+ patchCodegenUiState(widgetId, { generateCodeStatus: `❌ ${trackingLostText}` });
5948
+ }
5949
+ } finally {
5950
+ noteCodegenActive(false);
5951
+ // A generation this tab started on the widget since has taken the entries over: leave them alone
5952
+ if (widgetAbortControllers.get(widgetId) === controller) {
5953
+ widgetAbortControllers.delete(widgetId);
5954
+ followedGenerationWidgetIds.delete(widgetId);
5955
+ if (generationOperationByWidgetId.get(widgetId) === operationId) generationOperationByWidgetId.delete(widgetId);
5956
+ const { [widgetId]: _followed, ...stillGenerating } = generatingWidgetIds;
5957
+ generatingWidgetIds = stillGenerating;
5958
+ }
5959
+ if (currentGenerationOperationId === operationId) currentGenerationOperationId = null;
5960
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
5877
5961
  }
5962
+ if (endedOperation) await finishFollowedGeneration(widgetId, operationId, endedOperation, true);
5963
+ } catch (error) {
5964
+ console.warn('[GenerationSharing] Could not follow a generation', { widgetId, operationId, origin, error });
5965
+ } finally {
5966
+ widgetsBeingJoined.delete(widgetId);
5967
+ }
5968
+ }
5878
5969
 
5879
- // Still running — resume polling UI
5880
- // console.log(`[GenerationResilience] Generation still in progress (${status}, ${op?.progress || 0}%). Resuming polling...`);
5881
- isCheckingActiveGeneration = false; // Check done — now isGeneratingCode takes over
5882
- isGeneratingCode = true;
5883
- lastGenerationFailed = false;
5884
- lastGenerationError = null;
5885
- generateCodeStatus = `Reconnected — code generation in progress... ${op?.progress || 0}%`;
5970
+ /**
5971
+ * Shows how a generation that this tab followed, or found already ended, ended. `announce` is false when nobody was waiting
5972
+ * for the news (the tab only learned of a generation that was over): then a finished generation still brings the widget up to
5973
+ * date, and a failed or stopped one says nothing. It adds nothing to the conversation: the tab that ran the generation
5974
+ * saved what there is to save, and this tab reads it back.
5975
+ */
5976
+ async function finishFollowedGeneration(
5977
+ widgetId: string,
5978
+ operationId: string,
5979
+ operation: OperationSnapshot,
5980
+ announce: boolean
5981
+ ): Promise<void> {
5982
+ void forgetStoredOperationId(widgetId, operationId);
5983
+ const panelChat = getChatMethodsForWidget(widgetId);
5886
5984
 
5887
- // Close preview modal if open — generation isn't done yet, preview would show stale content
5888
- if (showPreviewModal) {
5889
- showPreviewModal = false;
5890
- // console.log('[GenerationResilience] Closed preview modal — generation still in progress');
5891
- }
5892
-
5893
- // Keep preview tab so user sees the "Generating..." overlay
5894
- widgetDetails?.setInlinePanelView('preview');
5985
+ if (operation.status === 'cancelled') {
5986
+ if (!announce) return;
5987
+ patchCodegenUiState(widgetId, { generateCodeStatus: '⏹ Generation stopped by user' });
5988
+ panelChat?.updateLatestCodegenStatusMessage?.('Generation stopped by user. You can Retry this prompt.');
5989
+ showToast('info', $t('creator.codegen.generationStopped'), {
5990
+ description: $t('creator.codegen.codeGenerationWasCancelledYou'),
5991
+ duration: 3000
5992
+ });
5993
+ return;
5994
+ }
5895
5995
 
5896
- showToast('info', $t('creator.codegen.generationInProgress'), {
5897
- description: $t('creator.codegen.reconnectedToAnActiveCode'),
5898
- duration: 4000
5996
+ if (operation.status === 'failed') {
5997
+ if (!announce) return;
5998
+ const failureText = operation.error || 'Unknown error';
5999
+ patchCodegenUiState(widgetId, {
6000
+ generateCodeStatus: '❌ Code generation failed',
6001
+ lastGenerationFailed: true,
6002
+ lastGenerationError: failureText,
5899
6003
  });
6004
+ panelChat?.updateLatestCodegenStatusMessage?.(`Code generation failed: ${failureText}`);
6005
+ showToast('error', $t('creator.status.failed'), { description: failureText, duration: 8000 });
6006
+ // What the other tab saved of the failure reaches this tab's conversation
6007
+ setTimeout(() => {
6008
+ void getChatMethodsForWidget(widgetId)?.reloadConversationMessages?.();
6009
+ }, 2500);
6010
+ return;
6011
+ }
5900
6012
 
5901
- // Create abort controller for this resumed generation
5902
- codeGenerationAbortController?.abort();
5903
- codeGenerationAbortController = new AbortController();
5904
- const signal = codeGenerationAbortController.signal;
6013
+ if (operation.status !== 'completed') return;
6014
+ const commitSha = getOperationCommitId(operation.metadata);
6015
+ const commitTitle = getOperationCommitTitle(operation.metadata);
6016
+ const panelHadPublishedVersion =
6017
+ getPanelState(widgetId).lastPublishedVersion !== null || getPanelDisplayState(widgetId).lastPublishedVersion !== null;
6018
+ if (commitSha) {
6019
+ saveCommitIdForWidget(widgetId, commitSha);
6020
+ stampCodegenTitleIntoPanelHistory(widgetId, commitSha, commitTitle);
6021
+ // The widget has a live version and the generation moved it on: Publish offers the new one
6022
+ if (panelHadPublishedVersion) savePendingPublishShaForWidget(widgetId, commitSha);
6023
+ }
6024
+ patchCodegenUiState(widgetId, {
6025
+ hasGeneratedCode: true,
6026
+ ...(commitSha ? { lastCommitId: commitSha } : {}),
6027
+ lastGenerationFailed: false,
6028
+ lastGenerationError: null,
6029
+ generateCodeStatus: 'Code saved — loading preview…',
6030
+ });
6031
+ if (panelHadPublishedVersion) patchPanelSnapshot(widgetId, { pendingPublishAfterCodegen: true });
6032
+ panelDisplayRevision += 1;
5905
6033
 
5906
- try {
5907
- await waitForOperation(operationId, (updatedOp) => {
5908
- if (signal.aborted) return;
5909
- if (!updatedOp) return;
5910
-
5911
- if (updatedOp.status === 'failed') {
5912
- const resumeError = updatedOp.error || 'Unknown error';
5913
- const isResumeServiceErr = resumeError.includes('temporarily unavailable') || resumeError.includes('Our team has been notified');
5914
- generateCodeStatus = `❌ Code generation failed`;
5915
- lastGenerationFailed = true;
5916
- lastGenerationError = resumeError;
5917
- clearActiveOperationId();
5918
- showToast('error', isResumeServiceErr ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
5919
- description: resumeError,
5920
- duration: isResumeServiceErr ? 10000 : 8000
5921
- });
5922
- return;
5923
- }
6034
+ if (announce) {
6035
+ const isFocusedPanel = widgetId === focusedPanelWidgetId;
6036
+ const completedWidgetName = getWidgetById(widgetId)?.name || 'widget';
6037
+ showToast(
6038
+ 'success',
6039
+ isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
6040
+ {
6041
+ description: isFocusedPanel ? $t('creator.codegen.codeSavedToGitlabAnd') : $t('creator.general.switchToThatPanelTo'),
6042
+ duration: 5000
6043
+ }
6044
+ );
6045
+ }
6046
+ setTimeout(() => {
6047
+ void refreshWidgetAfterRemoteGeneration(widgetId);
6048
+ }, 800);
6049
+ }
5924
6050
 
5925
- if (updatedOp.status === 'completed') {
5926
- clearActiveOperationId();
5927
-
5928
- if (selectedWidgetId !== resumeWidgetId) {
5929
- // console.log('[GenerationResilience] Completed for widget', resumeWidgetId, 'but user switched to', selectedWidgetId);
5930
- showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5931
- description: $t('creator.codegen.generationFinishedForADifferent'),
5932
- duration: 5000
5933
- });
5934
- return;
5935
- }
5936
-
5937
- hasChangesToSave = false;
5938
- generateCodeStatus = 'Code generation completed! Saved to GitLab.';
5939
- showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5940
- description: $t('creator.codegen.codeSavedToGitlabAnd'),
5941
- duration: 5000
5942
- });
5943
- setTimeout(async () => {
5944
- if (selectedWidgetId !== resumeWidgetId) return;
5945
- widgetDetails?.setInlinePanelView('preview');
5946
- widgetDetails?.setHasAutoOpenedPreview(true);
5947
- await widgetDetails?.refreshPreview({ withRetry: true });
5948
- generateCodeStatus = 'Code generation completed! Saved to GitLab.';
5949
- }, 2500);
5950
- } else {
5951
- pushCodegenProgressToUi(updatedOp, resumeWidgetId);
5952
- }
5953
- }, signal);
5954
- } catch (err) {
5955
- if (err instanceof DOMException && err.name === 'AbortError') {
5956
- // console.log('[GenerationResilience] Resumed generation polling was aborted');
5957
- return;
6051
+ /**
6052
+ * Brings a widget up to date after a generation that another tab ran (or that finished while this tab was away): the version
6053
+ * menu, the controls' schemas, the preview and the conversation, all read from the server. The tab that ran the generation
6054
+ * does the same for itself.
6055
+ */
6056
+ async function refreshWidgetAfterRemoteGeneration(widgetId: string): Promise<void> {
6057
+ try {
6058
+ const { [widgetId]: _resolved, ...restResolved } = shapeHistoryResolvedByWidgetId;
6059
+ shapeHistoryResolvedByWidgetId = restResolved;
6060
+ await loadPublishHistoryForPanel(widgetId, { silent: true });
6061
+ void loadWidgetSchemas(widgetId, { force: true });
6062
+
6063
+ const panelRef = getWidgetDetailsRef(widgetId);
6064
+ if (panelRef) {
6065
+ panelRef.setInlinePanelView('preview');
6066
+ panelRef.setHasAutoOpenedPreview(true);
6067
+ panelRef.markCodegenPreviewFresh?.();
6068
+ if (panelRef.hasLiveWorkerPreview?.()) {
6069
+ panelRef.setPreviewLoadingState(false);
6070
+ } else {
6071
+ panelRef.setPreviewLoadingState(true);
6072
+ await panelRef.refreshPreview?.({ withRetry: true, skipIfAlreadyShowing: true });
5958
6073
  }
5959
- console.error('[GenerationResilience] Error during resumed polling:', err);
5960
- const message = err?.message || 'Generation tracking lost.';
5961
- generateCodeStatus = `❌ ${message}`;
5962
- lastGenerationFailed = true;
5963
- lastGenerationError = message;
5964
- clearActiveOperationId();
5965
- } finally {
5966
- isGeneratingCode = false;
5967
- setCrossTabGenerating(false);
6074
+ panelRef.setPreviewBuildError(null);
5968
6075
  }
5969
- } catch (err) {
5970
- // console.log('[GenerationResilience] Failed to check operation status:', err?.message || err);
5971
- clearActiveOperationId();
5972
- } finally {
5973
- isCheckingActiveGeneration = false;
6076
+ shapePreviewSourceByWidgetId = { ...shapePreviewSourceByWidgetId, [widgetId]: 'preview' };
6077
+ syncWidgetShapeLivePreviews();
6078
+ widgetShapeLivePreviewsRef?.requestReload?.(widgetId);
6079
+ patchCodegenUiState(widgetId, { generateCodeStatus: 'Code generation completed! Preview ready.' });
6080
+ void refreshTrialCounter();
6081
+ setTimeout(async () => {
6082
+ try {
6083
+ const panelChat = getChatMethodsForWidget(widgetId);
6084
+ await panelChat?.reloadConversationMessages?.();
6085
+ panelChat?.markWidgetHeadAtLatestCommit?.();
6086
+ } catch (error) {
6087
+ console.warn('[GenerationSharing] Could not reload the conversation after a generation elsewhere', { widgetId, error });
6088
+ }
6089
+ }, 2500);
6090
+ } catch (error) {
6091
+ console.warn('[GenerationSharing] Could not bring the widget up to date after a generation elsewhere', { widgetId, error });
6092
+ }
6093
+ }
6094
+
6095
+ /** Follows the generation whose id this browser kept for the widget, when it has one (see `GenerationFollowOrigin`). */
6096
+ async function followStoredGeneration(widgetId: string): Promise<void> {
6097
+ try {
6098
+ const storedOperationId = await getStoredOperationId(widgetId);
6099
+ if (storedOperationId) await followGeneration(widgetId, storedOperationId, 'stored');
6100
+ } catch (error) {
6101
+ console.warn('[GenerationSharing] Could not look for a generation this browser kept for the widget', { widgetId, error });
6102
+ }
6103
+ }
6104
+
6105
+ /**
6106
+ * Asks the other tabs, and this browser's store, whether a generation is running on a widget this tab shows. Once per widget:
6107
+ * a tab that starts one later announces it, so asking again would only repeat what that announcement says.
6108
+ */
6109
+ function askAboutGenerationOnce(widgetId: string): void {
6110
+ // Not before the widget is known to this tab: the statement that calls this runs again when the widgets are loaded
6111
+ if (!getWidgetById(widgetId) || widgetsAskedAboutGeneration.has(widgetId)) return;
6112
+ widgetsAskedAboutGeneration.add(widgetId);
6113
+ generationChannel?.ask(widgetId);
6114
+ void followStoredGeneration(widgetId);
6115
+ }
6116
+
6117
+ /** A tab asked whether a generation runs on a widget: this tab says so when it runs, or follows, one. */
6118
+ function answerAboutGeneration(widgetId: string): void {
6119
+ const operationId = generationOperationByWidgetId.get(widgetId);
6120
+ if (operationId) generationChannel?.announceStarted(widgetId, operationId);
6121
+ }
6122
+
6123
+ /** Opens this tab's end of the channel between the tabs of the browser (a browser without one still reads its own store). */
6124
+ function openGenerationSharing(): void {
6125
+ if (generationSharingReady) return;
6126
+ try {
6127
+ generationChannel = openGenerationChannel({
6128
+ onStarted: (widgetId, operationId) => {
6129
+ void followGeneration(widgetId, operationId, 'announced');
6130
+ },
6131
+ onAsk: answerAboutGeneration
6132
+ });
6133
+ } catch (error) {
6134
+ console.warn('[GenerationSharing] Could not open the channel between the tabs', error);
6135
+ generationChannel = null;
6136
+ }
6137
+ // From now on the widgets this tab shows are asked about (see the statement that calls `askAboutGenerationOnce`)
6138
+ generationSharingReady = true;
6139
+ }
6140
+
6141
+ /** Closes the channel, and lets go of the generations this tab only followed (their jobs go on, on the server). */
6142
+ function closeGenerationSharing(): void {
6143
+ try {
6144
+ generationChannel?.close();
6145
+ } catch (error) {
6146
+ console.warn('[GenerationSharing] Could not close the channel between the tabs', error);
5974
6147
  }
6148
+ generationChannel = null;
6149
+ generationSharingReady = false;
6150
+ for (const widgetId of followedGenerationWidgetIds) widgetAbortControllers.get(widgetId)?.abort();
6151
+ followedGenerationWidgetIds.clear();
5975
6152
  }
5976
6153
 
5977
6154
  /* =======================================================================
@@ -6555,6 +6732,29 @@
6555
6732
  let canvasRowDeferred = false;
6556
6733
  let canvasRowCreatePromise: Promise<string | null> | null = null;
6557
6734
 
6735
+ const untitledCanvasBaseName = 'Untitled Widget';
6736
+
6737
+ function nextUntitledCanvasName(existingNames: string[]): string {
6738
+ const names = new Set(existingNames.map((name) => (name || '').trim()).filter(Boolean));
6739
+ if (!names.has(untitledCanvasBaseName)) return untitledCanvasBaseName;
6740
+ let highest = 1;
6741
+ for (const name of names) {
6742
+ const match = name.match(/^Untitled Widget (\d+)$/);
6743
+ if (!match) continue;
6744
+ const value = Number(match[1]);
6745
+ if (Number.isFinite(value) && value > highest) highest = value;
6746
+ }
6747
+ return `${untitledCanvasBaseName} ${highest + 1}`;
6748
+ }
6749
+
6750
+ function canvasCreateRequest(persistenceKey: string) {
6751
+ const trimmedProjectId = typeof projectId === 'string' ? projectId.trim() : '';
6752
+ return {
6753
+ persistenceKey,
6754
+ ...(trimmedProjectId ? { projectId: trimmedProjectId } : {})
6755
+ };
6756
+ }
6757
+
6558
6758
  async function ensureCanvasRowForFirstEdit(): Promise<string | null> {
6559
6759
  const existingId = typeof canvasId === 'string' ? canvasId.trim() : '';
6560
6760
  if (existingId) return existingId;
@@ -6565,15 +6765,9 @@
6565
6765
  return null;
6566
6766
  }
6567
6767
  try {
6568
- const usedNames = new Set(userCanvases.map((c) => (c.name || '').trim()).filter(Boolean));
6569
- let canvasIndex = userCanvases.length + 1;
6570
- let newName = `Canvas ${canvasIndex}`;
6571
- while (usedNames.has(newName)) {
6572
- canvasIndex += 1;
6573
- newName = `Canvas ${canvasIndex}`;
6574
- }
6768
+ const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
6575
6769
  const createdRaw = await canvasesClient.createCanvas({
6576
- createCanvasRequest: { persistenceKey: newName }
6770
+ createCanvasRequest: canvasCreateRequest(newName)
6577
6771
  });
6578
6772
  const createdId = unwrapCreatedCanvasId(createdRaw);
6579
6773
  if (!createdId) {
@@ -6613,17 +6807,9 @@
6613
6807
  }
6614
6808
 
6615
6809
  try {
6616
- // Names must be unique per user — duplicate keys ("Canvas 1" x N) made
6617
- // canvases indistinguishable and contributed to cross-canvas widget mix-ups.
6618
- const usedNames = new Set(userCanvases.map((c) => (c.name || '').trim()).filter(Boolean));
6619
- let canvasIndex = userCanvases.length + 1;
6620
- let newName = `Canvas ${canvasIndex}`;
6621
- while (usedNames.has(newName)) {
6622
- canvasIndex += 1;
6623
- newName = `Canvas ${canvasIndex}`;
6624
- }
6810
+ const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
6625
6811
  const createdRaw = await canvasesClient.createCanvas({
6626
- createCanvasRequest: { persistenceKey: newName }
6812
+ createCanvasRequest: canvasCreateRequest(newName)
6627
6813
  });
6628
6814
  const createdId = unwrapCreatedCanvasId(createdRaw);
6629
6815
  // console.log('[WidgetCreator] New canvas created:', createdId, newName, createdRaw);
@@ -8218,6 +8404,14 @@
8218
8404
  }
8219
8405
  };
8220
8406
 
8407
+ // Stopped before the wait began (Stop pressed while the request was being prepared): an abort event has already
8408
+ // happened and will not come again, so waiting for one would wait for ever
8409
+ if (signal?.aborted) {
8410
+ settled = true;
8411
+ reject(new DOMException('Operation aborted', 'AbortError'));
8412
+ return;
8413
+ }
8414
+
8221
8415
  // Handle abort signal
8222
8416
  if (signal) {
8223
8417
  signal.addEventListener('abort', () => {
@@ -8245,10 +8439,13 @@
8245
8439
  if (settled || signal?.aborted) return;
8246
8440
  pollAbortController = new AbortController();
8247
8441
  try {
8248
- const op = (await operationsClient.operationsIdGet(
8442
+ // The API wraps the operation in `{ success, data }`, which the generated client reads as an operation
8443
+ // with every field empty (a poll could then never see the end): the raw answer is read instead.
8444
+ const answer = await operationsClient.operationsIdGetRaw(
8249
8445
  { id: operationId },
8250
8446
  { signal: pollAbortController.signal }
8251
- )) as OperationStatus;
8447
+ );
8448
+ const op = (readOperationBody(await answer.raw.json()) ?? { status: 'running' }) as OperationStatus;
8252
8449
 
8253
8450
  // Check if aborted before processing
8254
8451
  if (signal?.aborted) {
@@ -8326,47 +8523,82 @@
8326
8523
  }
8327
8524
 
8328
8525
  /**
8329
- * Stop the current code generation process
8330
- * Aborts the polling and resets UI state
8526
+ * Stop the code generation of one panel. The job on the server is cancelled: a generation that is only walked away from
8527
+ * goes on writing, and spending credits, for as long as it takes. This tab stops waiting for it and shows the panel as
8528
+ * stopped at once; if the server could not be reached, or the job had ended already, the panel says so afterwards (see
8529
+ * `stopOperationOnServer`). Stop belongs to the panel it was pressed in, so the other panels' generations go on, and it
8530
+ * works the same on a generation this tab only follows because another tab began it.
8331
8531
  */
8332
- function stopGeneration() {
8333
- // Prefer the focused panel widget (Stop lives in that panel's Chat), then selected, then all in-flight.
8334
- const stopTargetIds = Array.from(
8335
- new Set(
8336
- [focusedPanelWidgetId, selectedWidgetId, ...Object.keys(generatingWidgetIds)].filter(
8337
- (id): id is string => typeof id === 'string' && id.length > 0,
8338
- ),
8339
- ),
8340
- );
8532
+ function stopGeneration(requestedWidgetId?: string | null) {
8533
+ // The panel whose Stop was pressed; failing that the panel in front, and then the first one that generates
8534
+ const stopWidgetId =
8535
+ requestedWidgetId || focusedPanelWidgetId || selectedWidgetId || Object.keys(generatingWidgetIds)[0] || null;
8536
+ if (!stopWidgetId) return;
8537
+
8538
+ // The job's id, when the server has named it: a run whose request is still on its way has none yet, and cancels
8539
+ // the job itself as soon as the server names it (see `performCodeGeneration`)
8540
+ const operationId = generationOperationByWidgetId.get(stopWidgetId) ?? null;
8341
8541
 
8342
- for (const widgetId of stopTargetIds) {
8343
- const controller = widgetAbortControllers.get(widgetId);
8542
+ try {
8543
+ const controller = widgetAbortControllers.get(stopWidgetId);
8344
8544
  if (controller) {
8545
+ abortControllersStoppedByUser.add(controller);
8345
8546
  controller.abort();
8346
- widgetAbortControllers.delete(widgetId);
8547
+ widgetAbortControllers.delete(stopWidgetId);
8347
8548
  }
8348
- clearActiveOperationId(widgetId);
8349
- }
8350
-
8351
- generatingWidgetIds = {};
8352
- // Legacy fallback
8353
- if (codeGenerationAbortController) {
8354
- codeGenerationAbortController.abort();
8355
- codeGenerationAbortController = null;
8549
+ followedGenerationWidgetIds.delete(stopWidgetId);
8550
+ generationOperationByWidgetId.delete(stopWidgetId);
8551
+ clearActiveOperationId(stopWidgetId);
8552
+ } catch (error) {
8553
+ console.warn('[GenerationStop] Could not let go of the generation in this tab', { widgetId: stopWidgetId, error });
8356
8554
  }
8357
8555
 
8358
- currentGenerationOperationId = null;
8359
- isGeneratingCode = false;
8360
- setCrossTabGenerating(false);
8361
- generateCodeStatus = '⏹ Generation stopped by user';
8362
- const statusWidgetId = focusedPanelWidgetId || selectedWidgetId || stopTargetIds[0] || null;
8363
- getChatMethodsForWidget(statusWidgetId)?.updateLatestCodegenStatusMessage?.(
8556
+ const { [stopWidgetId]: _stopped, ...stillGenerating } = generatingWidgetIds;
8557
+ generatingWidgetIds = stillGenerating;
8558
+ if (!operationId || currentGenerationOperationId === operationId) currentGenerationOperationId = null;
8559
+ // Only the generations of the panel in front count here: the panels that generate elsewhere keep their own state
8560
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
8561
+ setCrossTabGenerating(false, stopWidgetId);
8562
+ patchCodegenUiState(stopWidgetId, { generateCodeStatus: '⏹ Generation stopped by user' });
8563
+ getChatMethodsForWidget(stopWidgetId)?.updateLatestCodegenStatusMessage?.(
8364
8564
  'Generation stopped by user. You can Retry this prompt.',
8365
8565
  );
8366
8566
  showToast('info', $t('creator.codegen.generationStopped'), {
8367
8567
  description: $t('creator.codegen.codeGenerationWasCancelledYou'),
8368
8568
  duration: 3000
8369
8569
  });
8570
+
8571
+ if (operationId) void stopOperationOnServer(stopWidgetId, operationId);
8572
+ }
8573
+
8574
+ /**
8575
+ * Asks the server to cancel a generation's job. The panel shows the generation as stopped already (a press of Stop is
8576
+ * answered at once), so only what differs is said here: a job that had ended before the request arrived is shown as it
8577
+ * ended, and a job the server could not be asked to cancel is said to be possibly still running, and followed again, so
8578
+ * that Stop does not look done when it is not.
8579
+ */
8580
+ async function stopOperationOnServer(widgetId: string, operationId: string): Promise<void> {
8581
+ try {
8582
+ if (!operationsClient) return;
8583
+ const stopResult = await requestOperationStop(operationsClient, operationId);
8584
+ if (stopResult.outcome === 'stopped' || stopResult.outcome === 'gone') return;
8585
+ if (stopResult.outcome === 'already-ended') {
8586
+ await followGeneration(widgetId, operationId, 'stop-too-late');
8587
+ return;
8588
+ }
8589
+ console.warn('[GenerationStop] The server could not be asked to cancel the generation', {
8590
+ widgetId,
8591
+ operationId,
8592
+ error: stopResult.error
8593
+ });
8594
+ showToast('warning', $t('creator.codegen.couldNotStopGeneration'), {
8595
+ description: $t('creator.codegen.generationMayStillBeRunning'),
8596
+ duration: 8000
8597
+ });
8598
+ await followGeneration(widgetId, operationId, 'stop-failed');
8599
+ } catch (error) {
8600
+ console.warn('[GenerationStop] Stopping the generation on the server failed', { widgetId, operationId, error });
8601
+ }
8370
8602
  }
8371
8603
 
8372
8604
  // ============ IMAGE INPUT HELPERS ============
@@ -9491,6 +9723,21 @@ Requirements:
9491
9723
 
9492
9724
  $: if (focusedPanelWidgetId) rememberGenerationOptions(focusedPanelWidgetId);
9493
9725
 
9726
+ /**
9727
+ * Tells the creator's own preview frames to drop a screenshot they are taking: capturing while a generation runs freezes
9728
+ * the tab (the frames share its main thread). Used by a generation this tab starts and by one it follows.
9729
+ */
9730
+ function abortScreenshotsInFlight(): void {
9731
+ // The creator's own frames: in a partner's page `document` holds the page's frames, and not these.
9732
+ (getCreatorShadowRoot(creatorRootEl) ?? document).querySelectorAll('iframe').forEach((frame) => {
9733
+ try {
9734
+ frame.contentWindow?.postMessage({ type: 'widgetic:abort-screenshot' }, '*');
9735
+ } catch (err) {
9736
+ console.warn('[WidgetCreator] Could not abort in-flight screenshot', err);
9737
+ }
9738
+ });
9739
+ }
9740
+
9494
9741
  async function performCodeGeneration(
9495
9742
  prompt: string,
9496
9743
  options: {
@@ -9530,18 +9777,14 @@ Requirements:
9530
9777
  const abortController = new AbortController();
9531
9778
  widgetAbortControllers.set(generationWidgetId, abortController);
9532
9779
  const signal = abortController.signal;
9780
+ // A generation this tab only followed on the widget gives way to this one (its job is not this run's)
9781
+ followedGenerationWidgetIds.delete(generationWidgetId);
9782
+ generationOperationByWidgetId.delete(generationWidgetId);
9533
9783
 
9534
9784
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
9535
9785
  noteCodegenActive(true);
9536
9786
  screenshotGenerationEpoch += 1;
9537
- // The creator's own frames: in a partner's page `document` holds the page's frames, and not these.
9538
- (getCreatorShadowRoot(creatorRootEl) ?? document).querySelectorAll('iframe').forEach((frame) => {
9539
- try {
9540
- frame.contentWindow?.postMessage({ type: 'widgetic:abort-screenshot' }, '*');
9541
- } catch (err) {
9542
- console.warn('[WidgetCreator] Could not abort in-flight screenshot', err);
9543
- }
9544
- });
9787
+ abortScreenshotsInFlight();
9545
9788
  cancelQuietScreenshots();
9546
9789
  cancelIdleThumbnailPersist();
9547
9790
  widgetShapeLivePreviewsRef?.cancelReloads?.();
@@ -9765,6 +10008,8 @@ Requirements:
9765
10008
  ? undefined
9766
10009
  : resolvePlannerModelIdForGeneration(prompt, coderModelForRequest);
9767
10010
  const runtimeLogsForRequest = collectRuntimeLogsForCodegen(generationWidgetId);
10011
+ // Stopped, or replaced, while the request was being prepared: no job is started for a run nobody waits for
10012
+ if (signal.aborted) return;
9768
10013
  // The generated client types this call as void and drops the 202 body.
9769
10014
  // Read the raw JSON so operationId and the intent-gate payload survive.
9770
10015
  const accepted = await agentClient.agentCodeGeneratePostRaw({
@@ -9804,7 +10049,7 @@ Requirements:
9804
10049
  const gatedReply: string = gatedData.reply ?? '';
9805
10050
  const suggestions: ClarificationSuggestion[] = Array.isArray(gatedData.suggestions) ? gatedData.suggestions : [];
9806
10051
 
9807
- clearActiveOperationId();
10052
+ clearActiveOperationId(generationWidgetId);
9808
10053
  patchCodegenUiState(generationWidgetId, {
9809
10054
  lastGenerationFailed: false,
9810
10055
  lastGenerationError: null,
@@ -9898,6 +10143,15 @@ Requirements:
9898
10143
  return;
9899
10144
  }
9900
10145
 
10146
+ // Stop was pressed while the request was on its way, when there was no job to cancel yet. The server has named the
10147
+ // job now, so it is cancelled now; Stop has shown the panel as stopped already, so nothing more is shown here.
10148
+ if (abortControllersStoppedByUser.has(abortController)) {
10149
+ void stopOperationOnServer(generationWidgetId, operationId);
10150
+ return;
10151
+ }
10152
+ // Replaced by a newer run on the widget while the request was on its way: that run's job is the one that counts
10153
+ if (signal.aborted) return;
10154
+
9901
10155
  patchCodegenUiState(generationWidgetId, {
9902
10156
  generateCodeStatus: options.queued
9903
10157
  ? 'Processing queued code generation...'
@@ -9905,12 +10159,17 @@ Requirements:
9905
10159
  });
9906
10160
 
9907
10161
  // Persist operationId so we can reconnect after browser refresh
9908
- persistActiveOperationId(operationId);
10162
+ persistActiveOperationId(operationId, generationWidgetId);
9909
10163
  currentGenerationOperationId = operationId;
10164
+ // With the job named, Stop can cancel it, and the other tabs of this browser can follow it
10165
+ generationOperationByWidgetId.set(generationWidgetId, operationId);
10166
+ generationChannel?.announceStarted(generationWidgetId, operationId);
9910
10167
  getChatMethodsForWidget(generationWidgetId)?.updateLatestCodegenStatusMessage?.(
9911
10168
  'Code generation in progress...',
9912
10169
  );
9913
10170
 
10171
+ // The wait's callback sees the last frame of a stream twice: a job stopped elsewhere is shown as stopped once
10172
+ let cancelledElsewhereShown = false;
9914
10173
  await waitForOperation(operationId, (op) => {
9915
10174
  // Check if aborted before processing updates
9916
10175
  if (signal.aborted) return;
@@ -9923,7 +10182,7 @@ Requirements:
9923
10182
  lastGenerationFailed: true,
9924
10183
  lastGenerationError: errorMsg,
9925
10184
  });
9926
- clearActiveOperationId();
10185
+ clearActiveOperationId(generationWidgetId);
9927
10186
 
9928
10187
  const isServiceError = errorMsg.includes('temporarily unavailable') ||
9929
10188
  errorMsg.includes('Our team has been notified') ||
@@ -9955,8 +10214,24 @@ Requirements:
9955
10214
  return;
9956
10215
  }
9957
10216
 
10217
+ if (op.status === 'cancelled') {
10218
+ // Stopped from elsewhere: another tab of this browser pressed Stop on the generation this tab started (a Stop
10219
+ // pressed in this tab never gets here: it has aborted this wait). The panel shows it the way its own Stop does.
10220
+ clearActiveOperationId(generationWidgetId);
10221
+ if (!cancelledElsewhereShown) {
10222
+ cancelledElsewhereShown = true;
10223
+ patchCodegenUiState(generationWidgetId, { generateCodeStatus: '⏹ Generation stopped by user' });
10224
+ panelChat?.updateLatestCodegenStatusMessage?.('Generation stopped by user. You can Retry this prompt.');
10225
+ showToast('info', $t('creator.codegen.generationStopped'), {
10226
+ description: $t('creator.codegen.codeGenerationWasCancelledYou'),
10227
+ duration: 3000
10228
+ });
10229
+ }
10230
+ return;
10231
+ }
10232
+
9958
10233
  if (op.status === 'completed') {
9959
- clearActiveOperationId();
10234
+ clearActiveOperationId(generationWidgetId);
9960
10235
 
9961
10236
  const completedCommitSha = getOperationCommitId(op.metadata);
9962
10237
  const completedCommitTitle = getOperationCommitTitle(op.metadata);
@@ -10144,38 +10419,42 @@ Requirements:
10144
10419
  stampWidgetRepositoryId(generationWidgetId, completedRepoId);
10145
10420
  }
10146
10421
 
10422
+ const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
10423
+ const savedStatus = !completedCommitSha
10424
+ ? 'Code was not saved to the repository. Retry saves it and records a version.'
10425
+ : completedPreviewBuildErr
10426
+ ? `Code saved (${commitShort}) — building preview…`
10427
+ : `Code saved (${commitShort}) — loading preview…`;
10147
10428
  patchCodegenUiState(generationWidgetId, {
10148
10429
  hasGeneratedCode: true,
10149
10430
  ...(completedCommitSha ? { lastCommitId: completedCommitSha } : {}),
10150
- lastGenerationFailed: false,
10431
+ lastGenerationFailed: !completedCommitSha,
10151
10432
  lastGenerationError: completedPreviewBuildErr,
10152
- generateCodeStatus: completedPreviewBuildErr
10153
- ? `Code saved${completedCommitSha ? ` (${completedCommitSha.substring(0, 7)})` : ''} — building preview…`
10154
- : `Code saved${completedCommitSha ? ` (${completedCommitSha.substring(0, 7)})` : ''} — loading preview…`,
10433
+ generateCodeStatus: savedStatus,
10155
10434
  });
10156
10435
 
10157
- const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
10158
10436
  if (!completedCached) {
10159
- panelChat?.updateLatestCodegenStatusMessage?.(
10160
- completedPreviewBuildErr
10161
- ? `Code saved${commitShort ? ` (${commitShort})` : ''} — building preview…`
10162
- : `Code saved${commitShort ? ` (${commitShort})` : ''} — loading preview…`,
10163
- );
10437
+ panelChat?.updateLatestCodegenStatusMessage?.(savedStatus);
10164
10438
  }
10165
10439
 
10166
10440
  // console.log('Widget Creator: Code generation operation completed for widget', generationWidgetId.substring(0, 8), ':', op);
10167
10441
 
10168
- if (completedPreviewBuildErr) {
10442
+ if (completedPreviewBuildErr && completedCommitSha) {
10169
10443
  generationPanelRef?.setPreviewBuildError(null);
10170
10444
  generationPanelRef?.setPreviewLoadingState(true);
10171
10445
  panelChat?.addAssistantMessage(
10172
- `Code saved${completedCommitSha ? ` (Commit: ${completedCommitSha.substring(0, 7)})` : ''}, but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`,
10446
+ `Code saved (Commit: ${commitShort}), but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`,
10173
10447
  true
10174
10448
  );
10175
10449
  showToast('warning', $t('creator.codegen.codeSavedRebuildingPreview'), {
10176
10450
  description: completedPreviewBuildErr.length > 120 ? `${completedPreviewBuildErr.slice(0, 120)}…` : completedPreviewBuildErr,
10177
10451
  duration: 8000
10178
10452
  });
10453
+ } else if (!completedCommitSha) {
10454
+ showToast('warning', 'Code was not saved', {
10455
+ description: 'Retry saves it and records a version.',
10456
+ duration: 8000
10457
+ });
10179
10458
  } else {
10180
10459
  showToast(
10181
10460
  'success',
@@ -10202,14 +10481,16 @@ Requirements:
10202
10481
  // generation just happened.
10203
10482
  panelChat?.addAssistantMessage(
10204
10483
  cachedChatSummary ??
10205
- (completedPreviewBuildErr
10206
- ? `Code saved${completedCommitSha ? ` (Commit: ${completedCommitSha.substring(0, 7)})` : ''}, but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`
10207
- : `Code generation completed!${completedCommitSha ? ` Commit: ${completedCommitSha.substring(0, 7)}` : ''}\nPreview is loading…`),
10484
+ (!completedCommitSha
10485
+ ? 'Code was not saved to the repository. Retry saves it and records a version.'
10486
+ : completedPreviewBuildErr
10487
+ ? `Code saved (Commit: ${commitShort}), but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`
10488
+ : `Code generation completed! Commit: ${commitShort}\nPreview is loading…`),
10208
10489
  true
10209
10490
  );
10210
- if (!completedPreviewBuildErr && !completedCached) {
10491
+ if (!completedPreviewBuildErr && !completedCached && completedCommitSha) {
10211
10492
  panelChat?.updateLatestCodegenStatusMessage?.(
10212
- `Code generation completed!${completedCommitSha ? ` Commit: ${completedCommitSha.substring(0, 7)}` : ''}\nPreview is loading…`,
10493
+ `Code generation completed! Commit: ${commitShort}\nPreview is loading…`,
10213
10494
  );
10214
10495
  }
10215
10496
 
@@ -10386,17 +10667,23 @@ Requirements:
10386
10667
  lastGenerationFailed: true,
10387
10668
  lastGenerationError: message,
10388
10669
  });
10389
- clearActiveOperationId(); // Clear persisted operationId on error
10670
+ clearActiveOperationId(generationWidgetId); // Clear persisted operationId on error
10390
10671
  showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
10391
10672
  pushCodegenFailureToChat(generationWidgetId, message);
10392
10673
  } finally {
10393
10674
  noteCodegenActive(false);
10394
- const { [generationWidgetId]: _done, ...restFinally } = generatingWidgetIds;
10395
- generatingWidgetIds = restFinally;
10396
- widgetAbortControllers.delete(generationWidgetId);
10397
- // Update global flag: true only if the CURRENT widget is still generating
10398
- isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10399
- setCrossTabGenerating(false, generationWidgetId);
10675
+ // A run that was stopped or replaced reaches this point after its panel moved on: Stop has cleared the entries
10676
+ // already, and a newer run on the widget may have taken them over, so only a run that still holds them clears them.
10677
+ if (widgetAbortControllers.get(generationWidgetId) === abortController) {
10678
+ const { [generationWidgetId]: _done, ...restFinally } = generatingWidgetIds;
10679
+ generatingWidgetIds = restFinally;
10680
+ widgetAbortControllers.delete(generationWidgetId);
10681
+ if (currentGenerationOperationId === generationOperationByWidgetId.get(generationWidgetId)) currentGenerationOperationId = null;
10682
+ generationOperationByWidgetId.delete(generationWidgetId);
10683
+ // Update global flag: true only if the CURRENT widget is still generating
10684
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10685
+ setCrossTabGenerating(false, generationWidgetId);
10686
+ }
10400
10687
  }
10401
10688
  }
10402
10689
 
@@ -10890,6 +11177,11 @@ Requirements:
10890
11177
  handleBeforeUnloadRef = handleBeforeUnload;
10891
11178
  }
10892
11179
 
11180
+ // The server's operation status says whether a generation runs, so a tab can follow one that another tab of this
11181
+ // browser began; the tabs tell each other about them over a channel (see `followGeneration`). It holds no state of its
11182
+ // own, so partner mode (whose storage is in memory) has it too.
11183
+ openGenerationSharing();
11184
+
10893
11185
  // Read canvas id from the route. The route path (`/canvas/<canvasId>`) is the
10894
11186
  // AUTHORITATIVE canvas (site links, refresh, deep-links); localStorage is only a
10895
11187
  // fallback and must never win over it.
@@ -11002,10 +11294,14 @@ Requirements:
11002
11294
  window.removeEventListener(HOST_REQUEST_CANVAS_WIDGETS_EVENT, handleHostRequestCanvasWidgetsEvent);
11003
11295
  window.removeEventListener(HOST_MOVE_CANVAS_FOLDER_EVENT, handleHostMoveCanvasFolderEvent);
11004
11296
  for (const wId of Object.keys(generatingWidgetIds)) {
11297
+ // A generation this tab only follows is the other tab's: its flag is that tab's to clear
11298
+ if (followedGenerationWidgetIds.has(wId)) continue;
11005
11299
  setCrossTabGenerating(false, wId);
11006
11300
  }
11007
11301
  if (isPublishing) setCrossTabPublishing(false);
11008
11302
  }
11303
+ // Let go of the channel and of the generations this tab only followed (their jobs go on, on the server)
11304
+ closeGenerationSharing();
11009
11305
  // Partner mode ends with the creator: the token pump stops, and nothing the creator holds about this visitor
11010
11306
  // outlives it (the page may start the next visitor in the same tab). Last, because the cleanup above still
11011
11307
  // writes through the same storage.
@@ -13952,6 +14248,14 @@ $: if ($codeGenerationStatus.timestamp) {
13952
14248
  }
13953
14249
  }
13954
14250
 
14251
+ // A widget this tab shows may have a generation running that another tab of this browser began, or whose id this browser kept (the
14252
+ // tab was refreshed). The tab asks once per widget, once the channel is open and the widget is known: this statement runs again
14253
+ // when either arrives, or when the tab shows another widget (see `followGeneration`).
14254
+ $: if (generationSharingReady && widgetsById.size > 0) {
14255
+ if (focusedPanelWidgetId) askAboutGenerationOnce(focusedPanelWidgetId);
14256
+ if (selectedWidgetId && selectedWidgetId !== focusedPanelWidgetId) askAboutGenerationOnce(selectedWidgetId);
14257
+ }
14258
+
13955
14259
  // React to widget_publish_status 'building' events — disable Publish in other tabs
13956
14260
  $: if ($widgetPublishStatus.widgetId === selectedWidgetId && $widgetPublishStatus.status === 'building' && !isPublishing) {
13957
14261
  isPublishingInOtherTab = true;
@@ -17672,7 +17976,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17672
17976
  isGenerating={!!generatingWidgetIds[panelWidgetId]}
17673
17977
  onStopGeneration={() => {
17674
17978
  if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
17675
- stopGeneration();
17979
+ // Stop belongs to the panel it was pressed in: the other panels' generations go on
17980
+ stopGeneration(panelWidgetId);
17676
17981
  }}
17677
17982
  onStatsUpdate={(messageCount, firstMessage) => {
17678
17983
  // console.log('[Chat] Stats update:', { messageCount, firstMessage });