Skip to content
40 changes: 19 additions & 21 deletions src/lib/acode.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,20 @@ import fonts from "lib/fonts";
import fullscreen from "lib/fullscreen";
import {
BROKEN_PLUGINS,
isInitialPluginLoadComplete,
isPluginLoading,
LOADED_PLUGINS,
onPluginLoadCallback,
onPluginLoadFailedCallback,
onPluginsLoadCompleteCallback,
} from "lib/loadPlugins";
import notificationManager from "lib/notificationManager";
import openFolder, { addedFolder } from "lib/openFolder";
import orientation from "lib/orientation";
import PluginWaiters, {
pluginLoadError,
waitForPlugin as waitForPluginResult,
} from "lib/pluginWaiters";
import projects from "lib/projects";
import selectionMenu from "lib/selectionMenu";
import appSettings from "lib/settings";
Expand Down Expand Up @@ -97,7 +104,7 @@ class Acode {
#pluginUnmount = {};
// Registered formatter implementations (populated by plugins)
#formatter = [];
#pluginWatchers = {};
#pluginWatchers = new PluginWaiters();

/**
* Clear a plugin's broken mark (so it can be retried)
Expand Down Expand Up @@ -702,31 +709,22 @@ class Acode {
}

[onPluginLoadCallback](pluginId) {
if (this.#pluginWatchers[pluginId]) {
this.#pluginWatchers[pluginId].resolve();
delete this.#pluginWatchers[pluginId];
}
this.#pluginWatchers.resolve(pluginId, true);
}

[onPluginsLoadCompleteCallback]() {
for (const pluginId in this.#pluginWatchers) {
this.#pluginWatchers[pluginId].reject(
new Error(`Plugin '${pluginId}' failed to load.`),
);
}
this.#pluginWatchers = {};
[onPluginLoadFailedCallback](pluginId, error) {
this.#pluginWatchers.reject(pluginId, error || pluginLoadError(pluginId));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Errors lose the plugin name

When a plugin throws during loading, onPluginLoadFailedCallback rejects its waiters with the original error instead of the existing plugin-specific error promised by this PR. An error such as “Syntax error” no longer identifies which plugin failed. Reject with pluginLoadError(pluginId) and keep the original error as its cause.

}

waitForPlugin(pluginId) {
return new Promise((resolve, reject) => {
if (LOADED_PLUGINS.has(pluginId)) {
return resolve(true);
}
[onPluginsLoadCompleteCallback](filter) {
this.#pluginWatchers.rejectAll(pluginLoadError, filter);
}

this.#pluginWatchers[pluginId] = {
resolve,
reject,
};
waitForPlugin(pluginId) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the initial load has already completed (isInitialPluginLoadComplete()), a call for a plugin that's broken/disabled/not installed registers a waiter that will never settle — no further onPluginsLoadCompleteCallback runs, so the caller hangs silently.

Since this function is being rewritten anyway, it'd be good to reject immediately in that case.

Related: with the new Set, repeated calls for a never-loaded ID now accumulate entries for the rest of the session (previously it was overwritten, so bounded at one per ID). Settling late callers immediately fixes both.

return waitForPluginResult(this.#pluginWatchers, pluginId, {
isLoaded: (id) => LOADED_PLUGINS.has(id),
isInitialPluginLoadComplete,
isPluginLoading,
});
}

Expand Down
17 changes: 15 additions & 2 deletions src/lib/loadPlugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,24 @@ const THEME_IDENTIFIERS = new Set([
]);

export const onPluginLoadCallback = Symbol("onPluginLoadCallback");
export const onPluginLoadFailedCallback = Symbol("onPluginLoadFailedCallback");
export const onPluginsLoadCompleteCallback = Symbol(
"onPluginsLoadCompleteCallback",
);

export const LOADED_PLUGINS = new Set();
export const BROKEN_PLUGINS = new Map();
const AUTO_DISABLED_PLUGINS = new Set();
const IN_FLIGHT_PLUGINS = new Set();
const PLUGIN_LOAD_TIMEOUT = 15000;
const PLUGIN_DISABLE_TIMEOUT = 60000;
let pluginDisabledUpdateQueue = Promise.resolve();
let initialPluginLoadComplete = false;

export function isPluginLoading(pluginId) {
return IN_FLIGHT_PLUGINS.has(pluginId);
}

class PluginLoadTimeoutError extends Error {
constructor() {
super("Plugin load timeout");
Expand Down Expand Up @@ -113,11 +119,13 @@ export default async function loadPlugins(loadOnlyTheme = false) {

await Promise.allSettled(loadPromises);

acode[onPluginsLoadCompleteCallback]();
return results.filter(Boolean).length;
} finally {
if (!loadOnlyTheme) {
initialPluginLoadComplete = true;
acode[onPluginsLoadCompleteCallback]?.(
(pluginId) => !IN_FLIGHT_PLUGINS.has(pluginId),
);
}
}
}
Expand All @@ -127,15 +135,18 @@ export function isInitialPluginLoadComplete() {
}

export async function loadPluginWithTimeout(pluginId, justInstalled = false) {
IN_FLIGHT_PLUGINS.add(pluginId);
const pluginState = { settled: false };
const pluginLoadPromise = loadPlugin(pluginId, justInstalled)
.catch(async (error) => {
pluginState.settled = true;
IN_FLIGHT_PLUGINS.delete(pluginId);
await markPluginBroken(pluginId, error);
throw error;
})
.then(async () => {
pluginState.settled = true;
IN_FLIGHT_PLUGINS.delete(pluginId);
await markPluginLoaded(pluginId, justInstalled);
});

Expand Down Expand Up @@ -164,7 +175,7 @@ export async function loadPluginWithTimeout(pluginId, justInstalled = false) {

async function markPluginLoaded(pluginId, justInstalled = false) {
LOADED_PLUGINS.add(pluginId);
acode[onPluginLoadCallback](pluginId);
acode[onPluginLoadCallback]?.(pluginId);

// clear broken mark if present
if (BROKEN_PLUGINS.has(pluginId)) {
Expand All @@ -178,6 +189,7 @@ async function markPluginLoaded(pluginId, justInstalled = false) {
}

async function markPluginBroken(pluginId, error) {
acode[onPluginLoadFailedCallback]?.(pluginId, error);
// mark plugin as broken to avoid repeated attempts until user intervenes
BROKEN_PLUGINS.set(pluginId, {
error: String(error.message || error),
Expand All @@ -197,6 +209,7 @@ function markPluginTimedOut(pluginId, pluginState) {
setTimeout(async () => {
try {
if (pluginState.settled || LOADED_PLUGINS.has(pluginId)) return;
IN_FLIGHT_PLUGINS.delete(pluginId);
await markPluginBroken(pluginId, new Error("Plugin load timeout"));
} catch (error) {
console.error(`Failed to disable timed out plugin ${pluginId}:`, error);
Expand Down
60 changes: 60 additions & 0 deletions src/lib/pluginWaiters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
export function pluginLoadError(pluginId) {
return new Error(`Plugin '${pluginId}' failed to load.`);
}

export function waitForPlugin(waiters, pluginId, state) {
if (state.isLoaded(pluginId)) return Promise.resolve(true);
if (state.isInitialPluginLoadComplete() && !state.isPluginLoading(pluginId)) {
return Promise.reject(pluginLoadError(pluginId));
}
return waiters.waitFor(pluginId);
}

export default class PluginWaiters {
#waiters = new Map();

waitFor(pluginId) {
let deferred = this.#waiters.get(pluginId);
if (!deferred) {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
deferred = { promise, resolve, reject };
this.#waiters.set(pluginId, deferred);
}
return deferred.promise;
}

resolve(pluginId, value = true) {
const deferred = this.#waiters.get(pluginId);
if (!deferred) return;

this.#waiters.delete(pluginId);
deferred.resolve(value);
}

reject(pluginId, error) {
const deferred = this.#waiters.get(pluginId);
if (!deferred) return;

this.#waiters.delete(pluginId);
deferred.reject(error);
}

rejectAll(getError, filter) {
for (const [pluginId, deferred] of this.#waiters) {
if (filter && !filter(pluginId)) continue;
this.#waiters.delete(pluginId);
let error;
try {
error = getError(pluginId);
} catch (cause) {
error = cause instanceof Error ? cause : new Error(String(cause));
}
deferred.reject(error);
}
}
}
4 changes: 2 additions & 2 deletions src/pages/plugins/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import actionStack from "lib/actionStack";
import auth from "lib/auth";
import config from "lib/config";
import installPlugin from "lib/installPlugin";
import loadPlugin from "lib/loadPlugin";
import { loadPluginWithTimeout } from "lib/loadPlugins";
import settings from "lib/settings";
import FileBrowser from "pages/fileBrowser";
import Plugin from "pages/plugin";
Expand Down Expand Up @@ -809,7 +809,7 @@ export default function PluginsInclude(updates) {
} else {
delete disabledMap[id];
settings.update({ pluginsDisabled: disabledMap }, false);
await loadPlugin(id);
await loadPluginWithTimeout(id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Enable reports success after timeout

loadPluginWithTimeout returns false after 15 seconds, but this handler ignores the result and announces “Plugin enabled.” It then marks the plugin enabled in every displayed list. If the load never finishes, the loader later disables it, leaving the page showing success for an inactive plugin.

Check the result before announcing success or updating the lists. The sidebar enable handler also ignores this result.

Knowledge Base Used: Plugin lifecycle and extension management

window.toast(strings["plugin_enabled"] || "Plugin enabled");
}

Expand Down
4 changes: 2 additions & 2 deletions src/sidebarApps/extensions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import purchaseListener from "handlers/purchase";
import auth from "lib/auth";
import config from "lib/config";
import InstallState from "lib/installState";
import loadPlugin from "lib/loadPlugin";
import { loadPluginWithTimeout } from "lib/loadPlugins";
import settings from "lib/settings";
import { interstitialAd } from "lib/startAd";
import FileBrowser from "pages/fileBrowser";
Expand Down Expand Up @@ -1040,7 +1040,7 @@ async function more_plugin_action(id, pluginName) {
window.acode.unmountPlugin(id);
window.toast(strings["plugin_disabled"] || "Plugin Disabled");
} else {
await loadPlugin(id);
await loadPluginWithTimeout(id);
window.toast(strings["plugin_enabled"] || "Plugin enabled");
}
if (!$explore.collapsed) {
Expand Down
141 changes: 141 additions & 0 deletions tests/unit/loadPluginsWaiters.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

const mocks = vi.hoisted(() => ({
fsOperation: vi.fn(),
loadPlugin: vi.fn(),
settings: { value: { appTheme: "", pluginsDisabled: {} } },
}));

vi.mock("fileSystem", () => ({ default: mocks.fsOperation }));
vi.mock("lib/loadPlugin", () => ({ default: mocks.loadPlugin }));
vi.mock("lib/settings", () => ({ default: mocks.settings }));
vi.mock("utils/Url", () => ({
default: { basename: (url) => String(url).split("/").at(-1) },
}));

import {
isInitialPluginLoadComplete,
isPluginLoading,
LOADED_PLUGINS,
default as loadPlugins,
onPluginLoadCallback,
onPluginLoadFailedCallback,
onPluginsLoadCompleteCallback,
} from "lib/loadPlugins";
import PluginWaiters, {
pluginLoadError,
waitForPlugin,
} from "lib/pluginWaiters";

describe("plugin-load waiter integration", () => {
beforeEach(() => {
mocks.fsOperation.mockReset();
mocks.loadPlugin.mockReset();
globalThis.PLUGIN_DIR = "plugins/";
});

function useWaiters(waiters) {
globalThis.acode = {
waitForPlugin(pluginId) {
return waitForPlugin(waiters, pluginId, {
isLoaded: (id) => LOADED_PLUGINS.has(id),
isInitialPluginLoadComplete,
isPluginLoading,
});
},
[onPluginLoadCallback](pluginId) {
waiters.resolve(pluginId, true);
},
[onPluginLoadFailedCallback](pluginId, error) {
waiters.reject(pluginId, error);
},
[onPluginsLoadCompleteCallback](filter) {
waiters.rejectAll(pluginLoadError, filter);
},
};
}

it("does not reject regular plugin waiters after a theme-only pass", async () => {
globalThis.strings = { "loading plugins": "Loading plugins" };
globalThis.toast = vi.fn();
const waiters = new PluginWaiters();
useWaiters(waiters);
let settled = false;
const pending = globalThis.acode.waitForPlugin("regular-example").then(
(value) => {
settled = true;
return value;
},
(error) => {
settled = true;
return error;
},
);
const lsDir = vi
.fn()
.mockResolvedValue([
{ url: "plugins/theme-example" },
{ url: "plugins/regular-example" },
]);
mocks.fsOperation.mockReturnValue({ lsDir });
mocks.loadPlugin.mockResolvedValue(undefined);

await expect(loadPlugins(true)).resolves.toBe(1);
expect(isInitialPluginLoadComplete()).toBe(false);
expect(settled).toBe(false);
await loadPlugins();
expect(isInitialPluginLoadComplete()).toBe(true);
await expect(pending).resolves.toBe(true);
expect(mocks.loadPlugin).toHaveBeenCalledTimes(2);
expect(lsDir).toHaveBeenCalledTimes(2);
});

it("settles existing waiters when plugin discovery fails", async () => {
const waiters = new PluginWaiters();
const pending = waiters.waitFor("example");
useWaiters(waiters);
mocks.fsOperation.mockReturnValue({
lsDir: vi
.fn()
.mockRejectedValue(new Error("plugin directory unavailable")),
});

await expect(loadPlugins()).rejects.toThrow("plugin directory unavailable");
expect(isInitialPluginLoadComplete()).toBe(true);
await expect(pending).rejects.toThrow("Plugin 'example' failed to load.");
await expect(
globalThis.acode.waitForPlugin("not-installed"),
).rejects.toThrow("Plugin 'not-installed' failed to load.");
});

it("keeps waiters pending through a timed-out background load", async () => {
vi.useFakeTimers();
globalThis.strings = { "loading plugins": "Loading plugins" };
globalThis.toast = vi.fn();
const waiters = new PluginWaiters();
useWaiters(waiters);
let finishLoading;
mocks.loadPlugin.mockImplementation(
() => new Promise((resolve) => (finishLoading = resolve)),
);
mocks.fsOperation.mockReturnValue({
lsDir: vi.fn().mockResolvedValue([{ url: "plugins/slow-example" }]),
});
let waiterSettled = false;
const loading = loadPlugins();
const pending = globalThis.acode
.waitForPlugin("slow-example")
.then((value) => {
waiterSettled = true;
return value;
});
await vi.advanceTimersByTimeAsync(15_000);
await expect(loading).resolves.toBe(0);
expect(waiterSettled).toBe(false);

finishLoading();
await expect(pending).resolves.toBe(true);
vi.clearAllTimers();
vi.useRealTimers();
});
});
Loading