From d5cc5f568ead6e6c44940eab99842e92e6cc1037 Mon Sep 17 00:00:00 2001 From: makermelissa-ai-assistant <276182804+makermelissa-ai-assistant@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:36:20 -0800 Subject: [PATCH 1/2] Fix workflow switching and scope BLE partial writes --- js/common/ble-file-transfer.js | 4 +- js/common/utilities.js | 8 +- js/script.js | 188 ++++++++++++++++++++------------- js/workflows/usb.js | 2 +- 4 files changed, 121 insertions(+), 81 deletions(-) diff --git a/js/common/ble-file-transfer.js b/js/common/ble-file-transfer.js index 6b16775c..3e8fbf79 100644 --- a/js/common/ble-file-transfer.js +++ b/js/common/ble-file-transfer.js @@ -8,9 +8,11 @@ class FileTransferClient extends BLEFileTransferClient { constructor(bleDevice, bufferSize, workflow = null) { super(bleDevice, bufferSize); this._workflow = workflow; + this.mutationRevision = 0; } _signalMutatingOp() { + this.mutationRevision++; if (this._workflow && typeof this._workflow.markMutatingOp === 'function') { this._workflow.markMutatingOp(); } @@ -100,4 +102,4 @@ class FileTransferClient extends BLEFileTransferClient { } } -export {FileTransferClient}; \ No newline at end of file +export {FileTransferClient}; diff --git a/js/common/utilities.js b/js/common/utilities.js index afa97805..b3055aa2 100644 --- a/js/common/utilities.js +++ b/js/common/utilities.js @@ -130,7 +130,7 @@ function getUrlParam(name, remove = true) { } // Switch to a new url with the current document state and reload the page if the host and path are the same -function switchUrl(url, documentState, backend = null) { +function switchUrl(url, documentState, backend = null, {preserveUnloadWarning = false} = {}) { let params ={state: encodeURIComponent(JSON.stringify(documentState))} if (backend) { params.backend = backend; @@ -138,7 +138,9 @@ function switchUrl(url, documentState, backend = null) { let server = makeUrl(url, params); let oldHost = window.location.host; let oldPath = window.location.pathname; - window.onbeforeunload = () => {}; + if (!preserveUnloadWarning) { + window.onbeforeunload = () => {}; + } window.location.href = server; let serverUrl = new URL(server); if (serverUrl.host == oldHost && serverUrl.pathname == oldPath) { @@ -204,4 +206,4 @@ export { readUploadedFileAsArrayBuffer, loadSetting, saveSetting -}; \ No newline at end of file +}; diff --git a/js/script.js b/js/script.js index 7c497094..8e78b10d 100644 --- a/js/script.js +++ b/js/script.js @@ -41,11 +41,11 @@ workflows[CONNTYPE.Usb] = new USBWorkflow(); workflows[CONNTYPE.Web] = new WebWorkflow(); let workflow = null; -// Length of the leading run of bytes known to match what is on the device, used -// as the offset for partial writes. It is only meaningful for one particular -// file, so `unchangedPath` records which -- see saveFileContents(). +let workflowSelection = 0; +// The editor's dirty state and URL handoff use the saved prefix. +// Partial writes use only bytes confirmed on the current file-transfer connection. let unchanged = 0; -let unchangedPath = null; +let lastWrite = null; let connectionPromise = null; let debugMessageAnsi = null; let formatterInitPromise = null; @@ -730,12 +730,18 @@ async function newFile() { async function saveRunFile() { if (await checkConnected()) { + const savingWorkflow = workflow; + const selection = workflowSelection; + const fileHelper = savingWorkflow.fileHelper; + const tab = getActiveTab(); // workflow.saveFile() now propagates the real save result -- only // soft-restart / re-import once the PUT actually succeeded. Otherwise // we would reboot the board running the old code.py while the editor // still had the unsaved edits (issue #460). - if (await workflow.saveFile()) { - await workflow.runCurrentCode(); + if (await savingWorkflow.saveFile() && workflowSelection === selection + && savingWorkflow.fileHelper === fileHelper && getActiveTab() === tab + && savingWorkflow.connectionStatus()) { + await savingWorkflow.runCurrentCode(); } } } @@ -755,15 +761,15 @@ function setSaved(saved) { renderEditorTabs(); } -async function checkConnected() { - if (!workflow || !workflow.connectionStatus()) { +async function checkConnected({chooseWorkflow = false} = {}) { + if (chooseWorkflow || !workflow?.connectionStatus()) { let connType; // Prefer the last backend the user successfully connected with // (issue #373) so clicking Connect after a disconnect skips the // chooser. The connect dialog itself has a "back" link that calls // chooseAndShowConnect() if the user wants to switch workflows. - const lastBackend = getLastBackend(); + const lastBackend = chooseWorkflow ? null : getLastBackend(); if (lastBackend) { connType = lastBackend; } else { @@ -772,10 +778,12 @@ async function checkConnected() { return false; } } - await loadWorkflow(connType); + if (!await loadWorkflow(connType)) { + return false; + } // Connect if we're local (Web Workflow Only) - if ((isLocal()) && workflow.host) { + if (workflow.type === CONNTYPE.Web && isLocal() && workflow.host) { if (await workflowConnect()) { await checkReadOnly(); } @@ -789,7 +797,7 @@ async function checkConnected() { // BLE/USB/Web all behave the same way after a fresh connect. } - return true; + return !!workflow?.connectionStatus(); } // Closes whatever connect dialog is open and re-opens the workflow chooser, @@ -799,15 +807,7 @@ async function chooseAndShowConnect() { if (workflow && workflow.connectDialog && workflow.connectDialog.isOpen()) { workflow.connectDialog.close(); } - let connType = await chooseConnection(); - if (!connType) { - return false; - } - await loadWorkflow(connType); - if (!workflow.connectionStatus()) { - await workflow.showConnect(getDocState()); - } - return true; + return await checkConnected({chooseWorkflow: true}); } function getDocState() { @@ -925,8 +925,22 @@ async function loadWorkflow(workflowType = null) { return false; } + const nextWorkflow = workflows[workflowType] ?? null; + if (workflow && nextWorkflow && workflow !== nextWorkflow + && workflowType !== CONNTYPE.Web && isLocal() && !window.isSecureContext) { + // The URL carries the active document. Retain the unload prompt if + // navigating would discard unsaved edits in another tab. + const preserveUnloadWarning = editorTabs.some(tab => tab.id !== activeEditorTabId && isTabDirty(tab)); + switchUrl("https://code.circuitpython.org", getDocState(), getWorkflowBackendName(workflowType), + {preserveUnloadWarning}); + return false; + } + // Unload anything from the current workflow if (workflow != null) { + if (nextWorkflow && workflow !== nextWorkflow) { + await workflow.disconnectButtonHandler(); + } // Update Workflow specific UI elements await workflow.deinit(); } @@ -937,28 +951,29 @@ async function loadWorkflow(workflowType = null) { console.log("Load different workflow"); if (workflow) { currentFilename = workflow.currentFilename; - - if (isLocal()) { - let url = "https://code.circuitpython.org"; - if (location.hostname == "localhost" || location.hostname == "127.0.0.1") { - url = `${location.protocol}//${location.host}`; - } - switchUrl(url, getDocState(), getWorkflowBackendName(workflowType)); - } } - workflow = workflows[workflowType]; + workflow = nextWorkflow; + workflowSelection++; + lastWrite = null; + const selection = workflowSelection; + btnSaveAs.forEach(element => element.disabled = false); + btnSaveRun.forEach(element => element.disabled = false); rememberLastBackend(workflowType); updateUIConnected(false); // Initialize the workflow await workflow.init({ terminal: state.terminal, terminalTitle: terminalTitle, - loadEditorFunc: loadEditor, + loadEditorFunc: () => workflowSelection === selection ? loadEditor() : undefined, debugLogFunc: debugLog, - disconnectFunc: disconnectCallback, + disconnectFunc: () => { + if (workflowSelection === selection) { + disconnectCallback(); + } + }, isDirtyFunc: isDirty, setFilenameFunc: setFilename, - saveFileFunc: saveFileContents, + saveFileFunc: path => saveFileContents(path, nextWorkflow, selection), loadFileFunc: loadFileContents, loadEditorContentsFunc: loadEditorContents, showMessageFunc: showMessage, @@ -977,8 +992,11 @@ async function loadWorkflow(workflowType = null) { } // Unload workflow workflow = null; + workflowSelection++; + lastWrite = null; updateUIConnected(false); } + return true; } const hotkeyMap = [ @@ -1031,7 +1049,6 @@ function loadEditorContents(content, path = null, saved = true) { // can correctly skip a no-op reconfigure. editorLanguagePath = path; unchanged = saved === true ? editor.state.doc.length : saved === false ? 0 : saved; - unchangedPath = path; const activeTab = getActiveTab(); if (activeTab) { activeTab.editorState = editor.state; @@ -1114,7 +1131,7 @@ async function loadEditor() { setSaved(!isDirty()); } - updateUIConnected(true); + updateUIConnected(!!workflow?.connectionStatus()); // Show the Device Info dialog once per fresh connect, regardless of // workflow (Web / USB / BLE). This is where the firmware-update @@ -1144,12 +1161,27 @@ function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } +function matchingWriteOffset(previous, contents) { + const limit = Math.min(previous.length, contents.length); + let offset = 0; + while (offset < limit && previous[offset] === contents[offset]) { + offset++; + } + // BLE encodes the prefix and suffix separately as UTF-8. + const lastCodeUnit = contents.charCodeAt(offset - 1); + return lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff ? offset - 1 : offset; +} + // Save the File Contents and update the UI. Returns true on success, false // on final failure (after all retries). Retries inline so callers (Save+Run, // hotkeys, dialogs) can actually await the outcome -- previously this used // a fire-and-forget setTimeout, which let Save+Run soft-restart the board // before the PUT had succeeded (issue #460). -async function saveFileContents(path) { +async function saveFileContents(path, savingWorkflow, selection) { + if (workflow !== savingWorkflow || workflowSelection !== selection + || !savingWorkflow.connectionStatus()) { + return false; + } if (saveInFlight) { // Re-entrant save (e.g. user mashing Ctrl-S / Save+Run). The first // call will report success/failure; the second would race the same @@ -1159,51 +1191,49 @@ async function saveFileContents(path) { } saveInFlight = true; try { - // If this is a different file, we write everything. The language - // plugin is refreshed by setFilename below (it routes through - // setEditorLanguageForPath), so no extra dispatch is needed here. - // - // Compare against unchangedPath, not workflow.currentFilename: - // saveFileAs() assigns currentFilename *before* calling us, so by this - // point the two always match and the reset never fired. `unchanged` - // then still described the previously open file, and Save As did a - // partial write at that file's offset into a brand-new one, leaving - // everything before the offset as whatever the fresh cluster held. - if (path !== unchangedPath) { - unchanged = 0; + const fileHelper = savingWorkflow.fileHelper; + const fileClient = savingWorkflow.partialWrites ? fileHelper.getFileClient() : null; + const tab = getActiveTab(); + const tabPath = tab?.path; + const doc = editor.state.doc; + const contents = doc.sliceString(0); + const saveContextIsCurrent = () => workflowSelection === selection + && savingWorkflow.fileHelper === fileHelper && getActiveTab() === tab && tab?.path === tabPath; + let offset = 0; + if (fileClient && lastWrite?.fileHelper === fileHelper && lastWrite.path === path + && lastWrite.revision === fileClient.mutationRevision) { + offset = matchingWriteOffset(lastWrite.contents, contents); } - let doc = editor.state.doc; - let contents = doc.sliceString(0); - let baseUnchanged = unchanged; - let docLengthAtStart = doc.length; + // A failed write may have changed the destination. Retries start at zero. + lastWrite = null; for (let attempt = 1; attempt <= MAX_SAVE_RETRIES; attempt++) { - // Recompute offset each attempt -- if onTextChange fired between - // retries, `unchanged` may have shrunk and we need to resend more. - let offset = 0; - if (workflow.partialWrites) { - offset = Math.min(baseUnchanged, unchanged); - console.log("sync starting at", offset, "to", editor.state.doc.length); - } - // Optimistically mark the bytes-being-sent as unchanged. If the - // write throws we'll roll back to baseUnchanged for the next try. - // Either way the offset now describes `path`, so record that. - unchanged = docLengthAtStart; - unchangedPath = path; try { - if (await workflow.writeFile(path, contents, offset)) { - setFilename(workflow.currentFilename); - setSaved(true); - return true; + const revision = fileClient?.mutationRevision; + const written = await savingWorkflow.writeFile(path, contents, offset); + if (!saveContextIsCurrent()) { + return false; + } + if (written) { + if (fileClient && fileClient.mutationRevision === revision + 1) { + lastWrite = {fileHelper, path, contents, revision: fileClient.mutationRevision}; + } + setFilename(path); + const saved = editor.state.doc === doc; + setSaved(saved); + return saved; } // writeFile returned a falsy value without throwing -- treat // as a soft failure and surface a message immediately. - await showMessage(`Saving file '${workflow.currentFilename}' failed.`); setSaved(false); + await showMessage(`Saving file '${path}' failed.`); return false; } catch (e) { console.error(`write failed (attempt ${attempt} of ${MAX_SAVE_RETRIES})`, e, e.stack); - unchanged = Math.min(baseUnchanged, unchanged); + if (!saveContextIsCurrent()) { + return false; + } + offset = 0; // If the device cleanly told us the filesystem is held by // someone else (most commonly USB-MSC: the host has // CIRCUITPY mounted), retrying won't help -- surface an @@ -1228,7 +1258,7 @@ async function saveFileContents(path) { // USB connection or a wall adapter. See #460 for // the full discussion. await showMessage( - `
Could not save '${workflow.currentFilename}'.
` + + `Could not save '${path}'.
` + `The board's filesystem is in read-only mode for web workflow. ` + `This happens whenever USB Mass Storage is enabled on the board ` + `(the default for most CircuitPython boards), whether or not a ` + @@ -1247,9 +1277,9 @@ async function saveFileContents(path) { } if (attempt < MAX_SAVE_RETRIES) { await sleep(SAVE_RETRY_DELAY_MS); - // Bail out if the user disconnected mid-retry. - if (!workflow || !workflow.connectionStatus()) { - setSaved(false); + // A different connection or tab may now own the editor. + if (!saveContextIsCurrent() || !savingWorkflow.connectionStatus() + || editor.state.doc !== doc) { return false; } } @@ -1258,7 +1288,7 @@ async function saveFileContents(path) { // All retries exhausted. Leave the editor marked dirty so the user // knows the file on the board is still stale. setSaved(false); - await showMessage(`Saving file '${workflow.currentFilename}' failed after multiple attempts. Check your connection and try again.`); + await showMessage(`Saving file '${path}' failed after multiple attempts. Check your connection and try again.`); return false; } finally { saveInFlight = false; @@ -1267,6 +1297,9 @@ async function saveFileContents(path) { // Load the File Contents and Path into the UI function loadFileContents(path, contents, saved = true) { + if (lastWrite?.path === path) { + lastWrite = null; + } const existingTab = findTabByPath(path); if (existingTab) { activateEditorTab(existingTab.id); @@ -1437,6 +1470,9 @@ document.addEventListener('DOMContentLoaded', async (event) => { if (workflow != null && workflow.connectionStatus()) { // If so, unload the current workflow await workflow.disconnectButtonHandler(null); + } else if (isLocal() && workflow?.type === CONNTYPE.Web) { + // Local Wi-Fi reconnect skips the dialog with the chooser link. + await chooseAndShowConnect(); } else { // If not, it should display the available connections await checkConnected(); @@ -1450,7 +1486,7 @@ document.addEventListener('DOMContentLoaded', async (event) => { await loadWorkflow(backend); // If we don't have all the info we need to connect let returnVal = await workflow.parseParams(); - if (returnVal === true && await workflowConnect() && workflow.type === CONNTYPE.Web) { + if (returnVal === true && workflow.type === CONNTYPE.Web && await workflowConnect()) { // We're connected, local, no errors, and using Web Workflow. // The Device Info dialog is opened from loadEditor() now, so we // just need to verify read-only state here. diff --git a/js/workflows/usb.js b/js/workflows/usb.js index d3c1971d..be69a228 100644 --- a/js/workflows/usb.js +++ b/js/workflows/usb.js @@ -40,7 +40,7 @@ class USBWorkflow extends Workflow { // This is called when a user clicks the main disconnect button async disconnectButtonHandler(e) { await super.disconnectButtonHandler(e); - if (this.connectionStatus()) { + if (this._serialDevice || this.connectionStatus()) { await this.onDisconnected(null, false); } } From 4dee2f66b9fb978d6ce306a0b5d1ad8be3daf91c Mon Sep 17 00:00:00 2001 From: makermelissa-ai-assistant <276182804+makermelissa-ai-assistant@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:41:28 -0800 Subject: [PATCH 2/2] Clarify BLE file change counter name --- js/common/ble-file-transfer.js | 5 +++-- js/script.js | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/js/common/ble-file-transfer.js b/js/common/ble-file-transfer.js index 3e8fbf79..672f8071 100644 --- a/js/common/ble-file-transfer.js +++ b/js/common/ble-file-transfer.js @@ -8,11 +8,12 @@ class FileTransferClient extends BLEFileTransferClient { constructor(bleDevice, bufferSize, workflow = null) { super(bleDevice, bufferSize); this._workflow = workflow; - this.mutationRevision = 0; + this.fileChangeAttempts = 0; } _signalMutatingOp() { - this.mutationRevision++; + // Even a failed operation may have changed the board's files. + this.fileChangeAttempts++; if (this._workflow && typeof this._workflow.markMutatingOp === 'function') { this._workflow.markMutatingOp(); } diff --git a/js/script.js b/js/script.js index 8e78b10d..9a065e75 100644 --- a/js/script.js +++ b/js/script.js @@ -1201,7 +1201,7 @@ async function saveFileContents(path, savingWorkflow, selection) { && savingWorkflow.fileHelper === fileHelper && getActiveTab() === tab && tab?.path === tabPath; let offset = 0; if (fileClient && lastWrite?.fileHelper === fileHelper && lastWrite.path === path - && lastWrite.revision === fileClient.mutationRevision) { + && lastWrite.fileChangeAttempts === fileClient.fileChangeAttempts) { offset = matchingWriteOffset(lastWrite.contents, contents); } // A failed write may have changed the destination. Retries start at zero. @@ -1209,14 +1209,14 @@ async function saveFileContents(path, savingWorkflow, selection) { for (let attempt = 1; attempt <= MAX_SAVE_RETRIES; attempt++) { try { - const revision = fileClient?.mutationRevision; + const attemptsBeforeWrite = fileClient?.fileChangeAttempts; const written = await savingWorkflow.writeFile(path, contents, offset); if (!saveContextIsCurrent()) { return false; } if (written) { - if (fileClient && fileClient.mutationRevision === revision + 1) { - lastWrite = {fileHelper, path, contents, revision: fileClient.mutationRevision}; + if (fileClient && fileClient.fileChangeAttempts === attemptsBeforeWrite + 1) { + lastWrite = {fileHelper, path, contents, fileChangeAttempts: fileClient.fileChangeAttempts}; } setFilename(path); const saved = editor.state.doc === doc;