@widgetic/creator 0.4.0 → 0.4.1

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,189 +5822,335 @@
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;
5803
-
5804
- const resumeWidgetId = selectedWidgetId;
5805
- isCheckingActiveGeneration = true;
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);
5806
5863
 
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 });
5974
6092
  }
5975
6093
  }
5976
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);
6147
+ }
6148
+ generationChannel = null;
6149
+ generationSharingReady = false;
6150
+ for (const widgetId of followedGenerationWidgetIds) widgetAbortControllers.get(widgetId)?.abort();
6151
+ followedGenerationWidgetIds.clear();
6152
+ }
6153
+
5977
6154
  /* =======================================================================
5978
6155
  * API Gateway Integration Helpers
5979
6156
  * ===================================================================== */
@@ -8218,6 +8395,14 @@
8218
8395
  }
8219
8396
  };
8220
8397
 
8398
+ // Stopped before the wait began (Stop pressed while the request was being prepared): an abort event has already
8399
+ // happened and will not come again, so waiting for one would wait for ever
8400
+ if (signal?.aborted) {
8401
+ settled = true;
8402
+ reject(new DOMException('Operation aborted', 'AbortError'));
8403
+ return;
8404
+ }
8405
+
8221
8406
  // Handle abort signal
8222
8407
  if (signal) {
8223
8408
  signal.addEventListener('abort', () => {
@@ -8245,10 +8430,13 @@
8245
8430
  if (settled || signal?.aborted) return;
8246
8431
  pollAbortController = new AbortController();
8247
8432
  try {
8248
- const op = (await operationsClient.operationsIdGet(
8433
+ // The API wraps the operation in `{ success, data }`, which the generated client reads as an operation
8434
+ // with every field empty (a poll could then never see the end): the raw answer is read instead.
8435
+ const answer = await operationsClient.operationsIdGetRaw(
8249
8436
  { id: operationId },
8250
8437
  { signal: pollAbortController.signal }
8251
- )) as OperationStatus;
8438
+ );
8439
+ const op = (readOperationBody(await answer.raw.json()) ?? { status: 'running' }) as OperationStatus;
8252
8440
 
8253
8441
  // Check if aborted before processing
8254
8442
  if (signal?.aborted) {
@@ -8326,47 +8514,82 @@
8326
8514
  }
8327
8515
 
8328
8516
  /**
8329
- * Stop the current code generation process
8330
- * Aborts the polling and resets UI state
8517
+ * Stop the code generation of one panel. The job on the server is cancelled: a generation that is only walked away from
8518
+ * goes on writing, and spending credits, for as long as it takes. This tab stops waiting for it and shows the panel as
8519
+ * stopped at once; if the server could not be reached, or the job had ended already, the panel says so afterwards (see
8520
+ * `stopOperationOnServer`). Stop belongs to the panel it was pressed in, so the other panels' generations go on, and it
8521
+ * works the same on a generation this tab only follows because another tab began it.
8331
8522
  */
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
- );
8523
+ function stopGeneration(requestedWidgetId?: string | null) {
8524
+ // The panel whose Stop was pressed; failing that the panel in front, and then the first one that generates
8525
+ const stopWidgetId =
8526
+ requestedWidgetId || focusedPanelWidgetId || selectedWidgetId || Object.keys(generatingWidgetIds)[0] || null;
8527
+ if (!stopWidgetId) return;
8341
8528
 
8342
- for (const widgetId of stopTargetIds) {
8343
- const controller = widgetAbortControllers.get(widgetId);
8529
+ // The job's id, when the server has named it: a run whose request is still on its way has none yet, and cancels
8530
+ // the job itself as soon as the server names it (see `performCodeGeneration`)
8531
+ const operationId = generationOperationByWidgetId.get(stopWidgetId) ?? null;
8532
+
8533
+ try {
8534
+ const controller = widgetAbortControllers.get(stopWidgetId);
8344
8535
  if (controller) {
8536
+ abortControllersStoppedByUser.add(controller);
8345
8537
  controller.abort();
8346
- widgetAbortControllers.delete(widgetId);
8538
+ widgetAbortControllers.delete(stopWidgetId);
8347
8539
  }
8348
- clearActiveOperationId(widgetId);
8349
- }
8350
-
8351
- generatingWidgetIds = {};
8352
- // Legacy fallback
8353
- if (codeGenerationAbortController) {
8354
- codeGenerationAbortController.abort();
8355
- codeGenerationAbortController = null;
8540
+ followedGenerationWidgetIds.delete(stopWidgetId);
8541
+ generationOperationByWidgetId.delete(stopWidgetId);
8542
+ clearActiveOperationId(stopWidgetId);
8543
+ } catch (error) {
8544
+ console.warn('[GenerationStop] Could not let go of the generation in this tab', { widgetId: stopWidgetId, error });
8356
8545
  }
8357
8546
 
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?.(
8547
+ const { [stopWidgetId]: _stopped, ...stillGenerating } = generatingWidgetIds;
8548
+ generatingWidgetIds = stillGenerating;
8549
+ if (!operationId || currentGenerationOperationId === operationId) currentGenerationOperationId = null;
8550
+ // Only the generations of the panel in front count here: the panels that generate elsewhere keep their own state
8551
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
8552
+ setCrossTabGenerating(false, stopWidgetId);
8553
+ patchCodegenUiState(stopWidgetId, { generateCodeStatus: '⏹ Generation stopped by user' });
8554
+ getChatMethodsForWidget(stopWidgetId)?.updateLatestCodegenStatusMessage?.(
8364
8555
  'Generation stopped by user. You can Retry this prompt.',
8365
8556
  );
8366
8557
  showToast('info', $t('creator.codegen.generationStopped'), {
8367
8558
  description: $t('creator.codegen.codeGenerationWasCancelledYou'),
8368
8559
  duration: 3000
8369
8560
  });
8561
+
8562
+ if (operationId) void stopOperationOnServer(stopWidgetId, operationId);
8563
+ }
8564
+
8565
+ /**
8566
+ * Asks the server to cancel a generation's job. The panel shows the generation as stopped already (a press of Stop is
8567
+ * answered at once), so only what differs is said here: a job that had ended before the request arrived is shown as it
8568
+ * ended, and a job the server could not be asked to cancel is said to be possibly still running, and followed again, so
8569
+ * that Stop does not look done when it is not.
8570
+ */
8571
+ async function stopOperationOnServer(widgetId: string, operationId: string): Promise<void> {
8572
+ try {
8573
+ if (!operationsClient) return;
8574
+ const stopResult = await requestOperationStop(operationsClient, operationId);
8575
+ if (stopResult.outcome === 'stopped' || stopResult.outcome === 'gone') return;
8576
+ if (stopResult.outcome === 'already-ended') {
8577
+ await followGeneration(widgetId, operationId, 'stop-too-late');
8578
+ return;
8579
+ }
8580
+ console.warn('[GenerationStop] The server could not be asked to cancel the generation', {
8581
+ widgetId,
8582
+ operationId,
8583
+ error: stopResult.error
8584
+ });
8585
+ showToast('warning', $t('creator.codegen.couldNotStopGeneration'), {
8586
+ description: $t('creator.codegen.generationMayStillBeRunning'),
8587
+ duration: 8000
8588
+ });
8589
+ await followGeneration(widgetId, operationId, 'stop-failed');
8590
+ } catch (error) {
8591
+ console.warn('[GenerationStop] Stopping the generation on the server failed', { widgetId, operationId, error });
8592
+ }
8370
8593
  }
8371
8594
 
8372
8595
  // ============ IMAGE INPUT HELPERS ============
@@ -9491,6 +9714,21 @@ Requirements:
9491
9714
 
9492
9715
  $: if (focusedPanelWidgetId) rememberGenerationOptions(focusedPanelWidgetId);
9493
9716
 
9717
+ /**
9718
+ * Tells the creator's own preview frames to drop a screenshot they are taking: capturing while a generation runs freezes
9719
+ * the tab (the frames share its main thread). Used by a generation this tab starts and by one it follows.
9720
+ */
9721
+ function abortScreenshotsInFlight(): void {
9722
+ // The creator's own frames: in a partner's page `document` holds the page's frames, and not these.
9723
+ (getCreatorShadowRoot(creatorRootEl) ?? document).querySelectorAll('iframe').forEach((frame) => {
9724
+ try {
9725
+ frame.contentWindow?.postMessage({ type: 'widgetic:abort-screenshot' }, '*');
9726
+ } catch (err) {
9727
+ console.warn('[WidgetCreator] Could not abort in-flight screenshot', err);
9728
+ }
9729
+ });
9730
+ }
9731
+
9494
9732
  async function performCodeGeneration(
9495
9733
  prompt: string,
9496
9734
  options: {
@@ -9530,18 +9768,14 @@ Requirements:
9530
9768
  const abortController = new AbortController();
9531
9769
  widgetAbortControllers.set(generationWidgetId, abortController);
9532
9770
  const signal = abortController.signal;
9771
+ // A generation this tab only followed on the widget gives way to this one (its job is not this run's)
9772
+ followedGenerationWidgetIds.delete(generationWidgetId);
9773
+ generationOperationByWidgetId.delete(generationWidgetId);
9533
9774
 
9534
9775
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
9535
9776
  noteCodegenActive(true);
9536
9777
  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
- });
9778
+ abortScreenshotsInFlight();
9545
9779
  cancelQuietScreenshots();
9546
9780
  cancelIdleThumbnailPersist();
9547
9781
  widgetShapeLivePreviewsRef?.cancelReloads?.();
@@ -9765,6 +9999,8 @@ Requirements:
9765
9999
  ? undefined
9766
10000
  : resolvePlannerModelIdForGeneration(prompt, coderModelForRequest);
9767
10001
  const runtimeLogsForRequest = collectRuntimeLogsForCodegen(generationWidgetId);
10002
+ // Stopped, or replaced, while the request was being prepared: no job is started for a run nobody waits for
10003
+ if (signal.aborted) return;
9768
10004
  // The generated client types this call as void and drops the 202 body.
9769
10005
  // Read the raw JSON so operationId and the intent-gate payload survive.
9770
10006
  const accepted = await agentClient.agentCodeGeneratePostRaw({
@@ -9804,7 +10040,7 @@ Requirements:
9804
10040
  const gatedReply: string = gatedData.reply ?? '';
9805
10041
  const suggestions: ClarificationSuggestion[] = Array.isArray(gatedData.suggestions) ? gatedData.suggestions : [];
9806
10042
 
9807
- clearActiveOperationId();
10043
+ clearActiveOperationId(generationWidgetId);
9808
10044
  patchCodegenUiState(generationWidgetId, {
9809
10045
  lastGenerationFailed: false,
9810
10046
  lastGenerationError: null,
@@ -9898,6 +10134,15 @@ Requirements:
9898
10134
  return;
9899
10135
  }
9900
10136
 
10137
+ // Stop was pressed while the request was on its way, when there was no job to cancel yet. The server has named the
10138
+ // job now, so it is cancelled now; Stop has shown the panel as stopped already, so nothing more is shown here.
10139
+ if (abortControllersStoppedByUser.has(abortController)) {
10140
+ void stopOperationOnServer(generationWidgetId, operationId);
10141
+ return;
10142
+ }
10143
+ // Replaced by a newer run on the widget while the request was on its way: that run's job is the one that counts
10144
+ if (signal.aborted) return;
10145
+
9901
10146
  patchCodegenUiState(generationWidgetId, {
9902
10147
  generateCodeStatus: options.queued
9903
10148
  ? 'Processing queued code generation...'
@@ -9905,12 +10150,17 @@ Requirements:
9905
10150
  });
9906
10151
 
9907
10152
  // Persist operationId so we can reconnect after browser refresh
9908
- persistActiveOperationId(operationId);
10153
+ persistActiveOperationId(operationId, generationWidgetId);
9909
10154
  currentGenerationOperationId = operationId;
10155
+ // With the job named, Stop can cancel it, and the other tabs of this browser can follow it
10156
+ generationOperationByWidgetId.set(generationWidgetId, operationId);
10157
+ generationChannel?.announceStarted(generationWidgetId, operationId);
9910
10158
  getChatMethodsForWidget(generationWidgetId)?.updateLatestCodegenStatusMessage?.(
9911
10159
  'Code generation in progress...',
9912
10160
  );
9913
10161
 
10162
+ // The wait's callback sees the last frame of a stream twice: a job stopped elsewhere is shown as stopped once
10163
+ let cancelledElsewhereShown = false;
9914
10164
  await waitForOperation(operationId, (op) => {
9915
10165
  // Check if aborted before processing updates
9916
10166
  if (signal.aborted) return;
@@ -9923,7 +10173,7 @@ Requirements:
9923
10173
  lastGenerationFailed: true,
9924
10174
  lastGenerationError: errorMsg,
9925
10175
  });
9926
- clearActiveOperationId();
10176
+ clearActiveOperationId(generationWidgetId);
9927
10177
 
9928
10178
  const isServiceError = errorMsg.includes('temporarily unavailable') ||
9929
10179
  errorMsg.includes('Our team has been notified') ||
@@ -9955,8 +10205,24 @@ Requirements:
9955
10205
  return;
9956
10206
  }
9957
10207
 
10208
+ if (op.status === 'cancelled') {
10209
+ // Stopped from elsewhere: another tab of this browser pressed Stop on the generation this tab started (a Stop
10210
+ // pressed in this tab never gets here: it has aborted this wait). The panel shows it the way its own Stop does.
10211
+ clearActiveOperationId(generationWidgetId);
10212
+ if (!cancelledElsewhereShown) {
10213
+ cancelledElsewhereShown = true;
10214
+ patchCodegenUiState(generationWidgetId, { generateCodeStatus: '⏹ Generation stopped by user' });
10215
+ panelChat?.updateLatestCodegenStatusMessage?.('Generation stopped by user. You can Retry this prompt.');
10216
+ showToast('info', $t('creator.codegen.generationStopped'), {
10217
+ description: $t('creator.codegen.codeGenerationWasCancelledYou'),
10218
+ duration: 3000
10219
+ });
10220
+ }
10221
+ return;
10222
+ }
10223
+
9958
10224
  if (op.status === 'completed') {
9959
- clearActiveOperationId();
10225
+ clearActiveOperationId(generationWidgetId);
9960
10226
 
9961
10227
  const completedCommitSha = getOperationCommitId(op.metadata);
9962
10228
  const completedCommitTitle = getOperationCommitTitle(op.metadata);
@@ -10386,17 +10652,23 @@ Requirements:
10386
10652
  lastGenerationFailed: true,
10387
10653
  lastGenerationError: message,
10388
10654
  });
10389
- clearActiveOperationId(); // Clear persisted operationId on error
10655
+ clearActiveOperationId(generationWidgetId); // Clear persisted operationId on error
10390
10656
  showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
10391
10657
  pushCodegenFailureToChat(generationWidgetId, message);
10392
10658
  } finally {
10393
10659
  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);
10660
+ // A run that was stopped or replaced reaches this point after its panel moved on: Stop has cleared the entries
10661
+ // already, and a newer run on the widget may have taken them over, so only a run that still holds them clears them.
10662
+ if (widgetAbortControllers.get(generationWidgetId) === abortController) {
10663
+ const { [generationWidgetId]: _done, ...restFinally } = generatingWidgetIds;
10664
+ generatingWidgetIds = restFinally;
10665
+ widgetAbortControllers.delete(generationWidgetId);
10666
+ if (currentGenerationOperationId === generationOperationByWidgetId.get(generationWidgetId)) currentGenerationOperationId = null;
10667
+ generationOperationByWidgetId.delete(generationWidgetId);
10668
+ // Update global flag: true only if the CURRENT widget is still generating
10669
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10670
+ setCrossTabGenerating(false, generationWidgetId);
10671
+ }
10400
10672
  }
10401
10673
  }
10402
10674
 
@@ -10890,6 +11162,11 @@ Requirements:
10890
11162
  handleBeforeUnloadRef = handleBeforeUnload;
10891
11163
  }
10892
11164
 
11165
+ // The server's operation status says whether a generation runs, so a tab can follow one that another tab of this
11166
+ // browser began; the tabs tell each other about them over a channel (see `followGeneration`). It holds no state of its
11167
+ // own, so partner mode (whose storage is in memory) has it too.
11168
+ openGenerationSharing();
11169
+
10893
11170
  // Read canvas id from the route. The route path (`/canvas/<canvasId>`) is the
10894
11171
  // AUTHORITATIVE canvas (site links, refresh, deep-links); localStorage is only a
10895
11172
  // fallback and must never win over it.
@@ -11002,10 +11279,14 @@ Requirements:
11002
11279
  window.removeEventListener(HOST_REQUEST_CANVAS_WIDGETS_EVENT, handleHostRequestCanvasWidgetsEvent);
11003
11280
  window.removeEventListener(HOST_MOVE_CANVAS_FOLDER_EVENT, handleHostMoveCanvasFolderEvent);
11004
11281
  for (const wId of Object.keys(generatingWidgetIds)) {
11282
+ // A generation this tab only follows is the other tab's: its flag is that tab's to clear
11283
+ if (followedGenerationWidgetIds.has(wId)) continue;
11005
11284
  setCrossTabGenerating(false, wId);
11006
11285
  }
11007
11286
  if (isPublishing) setCrossTabPublishing(false);
11008
11287
  }
11288
+ // Let go of the channel and of the generations this tab only followed (their jobs go on, on the server)
11289
+ closeGenerationSharing();
11009
11290
  // Partner mode ends with the creator: the token pump stops, and nothing the creator holds about this visitor
11010
11291
  // outlives it (the page may start the next visitor in the same tab). Last, because the cleanup above still
11011
11292
  // writes through the same storage.
@@ -13952,6 +14233,14 @@ $: if ($codeGenerationStatus.timestamp) {
13952
14233
  }
13953
14234
  }
13954
14235
 
14236
+ // A widget this tab shows may have a generation running that another tab of this browser began, or whose id this browser kept (the
14237
+ // tab was refreshed). The tab asks once per widget, once the channel is open and the widget is known: this statement runs again
14238
+ // when either arrives, or when the tab shows another widget (see `followGeneration`).
14239
+ $: if (generationSharingReady && widgetsById.size > 0) {
14240
+ if (focusedPanelWidgetId) askAboutGenerationOnce(focusedPanelWidgetId);
14241
+ if (selectedWidgetId && selectedWidgetId !== focusedPanelWidgetId) askAboutGenerationOnce(selectedWidgetId);
14242
+ }
14243
+
13955
14244
  // React to widget_publish_status 'building' events — disable Publish in other tabs
13956
14245
  $: if ($widgetPublishStatus.widgetId === selectedWidgetId && $widgetPublishStatus.status === 'building' && !isPublishing) {
13957
14246
  isPublishingInOtherTab = true;
@@ -17672,7 +17961,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17672
17961
  isGenerating={!!generatingWidgetIds[panelWidgetId]}
17673
17962
  onStopGeneration={() => {
17674
17963
  if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
17675
- stopGeneration();
17964
+ // Stop belongs to the panel it was pressed in: the other panels' generations go on
17965
+ stopGeneration(panelWidgetId);
17676
17966
  }}
17677
17967
  onStatsUpdate={(messageCount, firstMessage) => {
17678
17968
  // console.log('[Chat] Stats update:', { messageCount, firstMessage });