playcanvas-agent-bridge-cli 0.4.2 → 0.5.0

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.
@@ -140,11 +140,68 @@
140
140
  });
141
141
  }
142
142
 
143
+ async function callDaemon(path, method, body) {
144
+ const allowed =
145
+ (path === "/builder/jobs" && method === "POST") ||
146
+ (/^\/builder\/jobs\/[^/]+$/.test(path) && method === "GET");
147
+ if (!allowed) throw new Error("Unsupported pcbridge browser request.");
148
+ const payload = body && typeof body === "object" ? { ...body } : {};
149
+ if (method === "POST" && !payload.target && Number.isInteger(tabInfo.tabId)) {
150
+ payload.target = "tab:" + tabInfo.tabId;
151
+ }
152
+ const response = await requestRuntime({
153
+ type: "pcbridge:daemonRequest",
154
+ path,
155
+ method,
156
+ body: payload
157
+ });
158
+ if (!response) throw new Error("pcbridge extension background service is unavailable.");
159
+ if (!response.ok) {
160
+ const error = new Error(
161
+ (response.error && response.error.message) || "pcbridge daemon request failed."
162
+ );
163
+ if (response.error && response.error.code) error.code = response.error.code;
164
+ if (response.error && response.error.details !== undefined) {
165
+ error.details = response.error.details;
166
+ }
167
+ throw error;
168
+ }
169
+ return response.data;
170
+ }
171
+
172
+ async function handleDaemonRequest(message) {
173
+ try {
174
+ const data = await callDaemon(message.path, message.method || "GET", message.body || {});
175
+ window.postMessage({
176
+ channel: CHANNEL,
177
+ side: "isolated",
178
+ type: "daemon-response",
179
+ id: message.id,
180
+ ok: true,
181
+ data
182
+ }, "*");
183
+ } catch (error) {
184
+ window.postMessage({
185
+ channel: CHANNEL,
186
+ side: "isolated",
187
+ type: "daemon-response",
188
+ id: message.id,
189
+ ok: false,
190
+ error: serializeError(error)
191
+ }, "*");
192
+ }
193
+ }
194
+
143
195
  window.addEventListener("message", (event) => {
144
196
  if (event.source !== window) return;
145
197
  const message = event.data;
146
198
  if (!message || message.channel !== CHANNEL || message.side !== "main") return;
147
199
 
200
+ if (message.type === "daemon-request" && message.id) {
201
+ void handleDaemonRequest(message);
202
+ return;
203
+ }
204
+
148
205
  if (message.type === "ready") {
149
206
  sendTargetUpdate().catch((error) => {
150
207
  if (isExtensionContextInvalidated(error)) stopBridge();
package/extension/main.js CHANGED
@@ -7,7 +7,12 @@
7
7
 
8
8
  const MAX_LOGS = 500;
9
9
  const capturedLogs = [];
10
+ const daemonWaiters = new Map();
10
11
  let nextLogSeq = 1;
12
+ let builderPanel = null;
13
+ let builderRefreshTimer = null;
14
+ let selectedTemplateId = null;
15
+ let selectedTemplateAsset = null;
11
16
 
12
17
  function formatLogArg(value) {
13
18
  if (typeof value === "string") return value;
@@ -640,6 +645,84 @@
640
645
  };
641
646
  }
642
647
 
648
+ async function readAssetResource(params) {
649
+ const asset = requireEditorAsset(params.assetId);
650
+ const file = plainAssetJson(asset)?.file || {};
651
+ const allowedUrls = new Set();
652
+ if (file.url) allowedUrls.add(String(file.url));
653
+ for (const variant of Object.values(file.variants || {})) {
654
+ if (variant && variant.url) allowedUrls.add(String(variant.url));
655
+ }
656
+ if (asset.get("type") === "font" && file.url) {
657
+ const mapCount = Number(plainAssetJson(asset)?.data?.info?.maps?.length || 0);
658
+ for (let index = 1; index < mapCount; index += 1) {
659
+ allowedUrls.add(String(file.url).replace(/(\.[^.]*)$/, `${index}$1`));
660
+ }
661
+ }
662
+ const url = String(params.url || "");
663
+ if (!url || !allowedUrls.has(url)) {
664
+ throw new Error("Requested URL does not belong to asset " + params.assetId + ".");
665
+ }
666
+ const resolvedUrl = new URL(url, location.href);
667
+ const headers = {};
668
+ const accessToken = window.editor.api.globals.accessToken;
669
+ const playCanvasHost =
670
+ resolvedUrl.hostname === "playcanvas.com" || resolvedUrl.hostname.endsWith(".playcanvas.com");
671
+ if (accessToken && playCanvasHost) headers.Authorization = "Bearer " + accessToken;
672
+ const response = await fetch(resolvedUrl.href, { headers });
673
+ if (!response.ok) {
674
+ const body = await response.text().catch(() => "");
675
+ throw new Error(body || "Failed to download asset resource " + params.assetId + ".");
676
+ }
677
+ const bytes = new Uint8Array(await response.arrayBuffer());
678
+ return {
679
+ assetId: String(asset.get("id")),
680
+ mime: response.headers.get("content-type") || "application/octet-stream",
681
+ size: bytes.length,
682
+ base64: base64FromBytes(bytes)
683
+ };
684
+ }
685
+
686
+ async function writeAssetFile(params) {
687
+ const asset = requireEditorAsset(params.assetId);
688
+ if (asset.get("type") === "script") {
689
+ throw new Error("Use the script text writer for script assets: " + params.assetId);
690
+ }
691
+ const filename = String(
692
+ params.filename || asset.get("file.filename") || asset.get("name") || "asset.bin"
693
+ );
694
+ const bytes = bytesFromBase64(String(params.base64 || ""));
695
+ const form = new FormData();
696
+ form.append("filename", filename);
697
+ form.append(
698
+ "file",
699
+ new Blob([bytes], { type: params.mime || "application/octet-stream" }),
700
+ filename
701
+ );
702
+ const branchId =
703
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
704
+ (window.config && window.config.branch && window.config.branch.id);
705
+ if (branchId) form.append("branchId", String(branchId));
706
+ const headers = {};
707
+ const accessToken = window.editor.api.globals.accessToken;
708
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
709
+ const response = await fetch("/api/assets/" + encodeURIComponent(String(asset.get("id"))), {
710
+ method: "PUT",
711
+ headers,
712
+ body: form
713
+ });
714
+ const body = await response.json().catch(() => ({}));
715
+ if (!response.ok || body.error) {
716
+ throw new Error(body.error || "Failed to update asset file.");
717
+ }
718
+ return {
719
+ assetId: String(asset.get("id")),
720
+ filename,
721
+ size: bytes.length,
722
+ response: body
723
+ };
724
+ }
725
+
643
726
  async function writeScriptText(params) {
644
727
  const asset = requireEditorAsset(params.assetId);
645
728
  if (asset.get("type") !== "script") {
@@ -681,6 +764,103 @@
681
764
  };
682
765
  }
683
766
 
767
+ function plainAssetJson(asset) {
768
+ if (!asset) return null;
769
+ if (typeof asset.json === "function") return asset.json();
770
+ if (asset.observer && typeof asset.observer.json === "function") return asset.observer.json();
771
+ return null;
772
+ }
773
+
774
+ function collectAssetReferences(assets, value, ids, depth = 0) {
775
+ if (!value || typeof value !== "object" || depth > 100) return;
776
+ for (const [key, child] of Object.entries(value)) {
777
+ if (["id", "path", "uniqueId", "scope", "testTemplate"].includes(key)) continue;
778
+ if (Number.isInteger(child)) {
779
+ const referenced = assets.get(Number(child));
780
+ const id = String(child);
781
+ if (referenced && !ids.has(id)) {
782
+ ids.add(id);
783
+ collectAssetReferences(assets, plainAssetJson(referenced), ids, depth + 1);
784
+ }
785
+ } else if (child && typeof child === "object") {
786
+ collectAssetReferences(assets, child, ids, depth + 1);
787
+ }
788
+ }
789
+ }
790
+
791
+ function templateScriptNames(templateData) {
792
+ const names = new Set();
793
+ for (const entity of Object.values((templateData && templateData.entities) || {})) {
794
+ const scripts = entity && entity.components && entity.components.script &&
795
+ entity.components.script.scripts;
796
+ for (const name of Object.keys(scripts || {})) names.add(name);
797
+ }
798
+ return [...names];
799
+ }
800
+
801
+ function templateChildren(templateData) {
802
+ const ids = new Set();
803
+ for (const entity of Object.values((templateData && templateData.entities) || {})) {
804
+ const attributes = entity && entity.components && entity.components.script &&
805
+ entity.components.script.scripts &&
806
+ entity.components.script.scripts.sdsTinyRootHandler &&
807
+ entity.components.script.scripts.sdsTinyRootHandler.attributes;
808
+ if (attributes && attributes.type === "testTemplate" && Number.isInteger(attributes.testTemplate)) {
809
+ ids.add(String(attributes.testTemplate));
810
+ }
811
+ }
812
+ return [...ids];
813
+ }
814
+
815
+ function collectTemplateDependencies(params) {
816
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
817
+ throw new Error("Template builds require a ready PlayCanvas Editor target.");
818
+ }
819
+ const assets = window.editor.api.globals.assets;
820
+ const template = assets.get(Number(params.assetId));
821
+ if (!template || template.get("type") !== "template") {
822
+ throw new Error("Template asset not found: " + params.assetId);
823
+ }
824
+ const templateJson = plainAssetJson(template);
825
+ if (!templateJson || !templateJson.data) {
826
+ throw new Error("Template asset has no serializable data: " + params.assetId);
827
+ }
828
+
829
+ const ids = new Set();
830
+ collectAssetReferences(assets, templateJson.data, ids);
831
+ const scripts = [];
832
+ for (const name of templateScriptNames(templateJson.data)) {
833
+ const scriptAsset =
834
+ (typeof assets.getAssetForScript === "function" && assets.getAssetForScript(name)) ||
835
+ (window.editor.assets && typeof window.editor.assets.getAssetForScript === "function" &&
836
+ window.editor.assets.getAssetForScript(name)) ||
837
+ assets.list().find((asset) =>
838
+ asset.get("type") === "script" &&
839
+ (asset.get("name") === name || asset.get("data.scripts." + name) !== undefined)
840
+ );
841
+ if (!scriptAsset) continue;
842
+ const scriptJson = plainAssetJson(scriptAsset);
843
+ const filename = scriptJson && scriptJson.file && scriptJson.file.filename;
844
+ if (
845
+ name.startsWith("sds") ||
846
+ String(filename || (scriptJson && scriptJson.name) || "").startsWith("sds")
847
+ ) continue;
848
+ ids.add(String(scriptAsset.get("id")));
849
+ scripts.push({ name, assetId: String(scriptAsset.get("id")) });
850
+ }
851
+
852
+ return {
853
+ template: templateJson,
854
+ assets: [...ids].map((id) => plainAssetJson(assets.get(Number(id)))).filter(Boolean),
855
+ scripts,
856
+ childTemplateIds: templateChildren(templateJson.data),
857
+ projectUrl: window.config && window.config.project && window.config.project.id
858
+ ? "https://playcanvas.com/project/" + window.config.project.id + "/overview"
859
+ : null,
860
+ sceneUrl: location.href
861
+ };
862
+ }
863
+
684
864
  function withTimeout(promise, timeoutMs) {
685
865
  return new Promise((resolve, reject) => {
686
866
  const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
@@ -697,6 +877,187 @@
697
877
  });
698
878
  }
699
879
 
880
+ function daemonRequest(path, method, body, timeoutMs = 15000) {
881
+ const id = "daemon-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
882
+ return new Promise((resolve, reject) => {
883
+ const timer = setTimeout(() => {
884
+ daemonWaiters.delete(id);
885
+ reject(new Error("No response from the local pcbridge daemon."));
886
+ }, timeoutMs);
887
+ daemonWaiters.set(id, { resolve, reject, timer });
888
+ window.postMessage({
889
+ channel: CHANNEL,
890
+ side: "main",
891
+ type: "daemon-request",
892
+ id,
893
+ path,
894
+ method,
895
+ body: body || {}
896
+ }, "*");
897
+ });
898
+ }
899
+
900
+ function selectedAssetStateFromEditor() {
901
+ if (!window.editor) return { known: false, asset: null };
902
+ try {
903
+ const items = window.editor.call && window.editor.call("selector:items");
904
+ if (Array.isArray(items)) return { known: true, asset: items[0] || null };
905
+ } catch {
906
+ // Fall through to the public selection API.
907
+ }
908
+ const selection = window.editor.api && window.editor.api.globals &&
909
+ window.editor.api.globals.selection;
910
+ const items = selection && (
911
+ (Array.isArray(selection.items) && selection.items) ||
912
+ (typeof selection.list === "function" && selection.list()) ||
913
+ (typeof selection.get === "function" && selection.get())
914
+ );
915
+ return Array.isArray(items)
916
+ ? { known: true, asset: items[0] || null }
917
+ : { known: false, asset: null };
918
+ }
919
+
920
+ function destroyBuilderPanel() {
921
+ if (builderPanel && typeof builderPanel.destroy === "function") builderPanel.destroy();
922
+ builderPanel = null;
923
+ selectedTemplateId = null;
924
+ selectedTemplateAsset = null;
925
+ }
926
+
927
+ function builderPanelIsAttached(layout) {
928
+ if (!builderPanel || builderPanel.destroyed === true) return false;
929
+ if (builderPanel.dom && typeof builderPanel.dom.isConnected === "boolean") {
930
+ return builderPanel.dom.isConnected;
931
+ }
932
+ if ("parent" in builderPanel) return builderPanel.parent === layout;
933
+ return true;
934
+ }
935
+
936
+ function appendRow(pcui, container, labelText, control) {
937
+ const row = new pcui.Container();
938
+ row.flex = true;
939
+ row.flexDirection = "row";
940
+ row.append(new pcui.Label({ text: labelText }));
941
+ row.append(control);
942
+ container.append(row);
943
+ }
944
+
945
+ function showBuilderPanel(asset) {
946
+ const type = asset && typeof asset.get === "function" ? asset.get("type") : null;
947
+ const id = asset && typeof asset.get === "function" ? String(asset.get("id")) : null;
948
+ if (type !== "template" || !id) {
949
+ destroyBuilderPanel();
950
+ return;
951
+ }
952
+ const pcui = window.pcui;
953
+ const layout = window.editor && window.editor.call && window.editor.call("layout.attributes");
954
+ if (!pcui || !pcui.Container || !pcui.Button || !pcui.Label || !pcui.TextInput || !layout) return;
955
+ if (builderPanel && selectedTemplateId === id && builderPanelIsAttached(layout)) return;
956
+ destroyBuilderPanel();
957
+
958
+ const projectId = window.config && window.config.project && window.config.project.id
959
+ ? String(window.config.project.id)
960
+ : "project";
961
+ const suffixKey = `pcbridge:builder:${id}:suffix`;
962
+ const prefixKey = `pcbridge:builder:${projectId}:prefix`;
963
+ const container = new pcui.Container();
964
+ container.flex = true;
965
+ container.flexDirection = "column";
966
+ if (container.class && typeof container.class.add === "function") {
967
+ container.class.add("pcbridge-tiny-builder");
968
+ }
969
+ container.append(new pcui.Label({ text: "pcbridge Tiny Builder" }));
970
+ const prefixInput = new pcui.TextInput({ value: localStorage.getItem(prefixKey) || "" });
971
+ const suffixInput = new pcui.TextInput({ value: localStorage.getItem(suffixKey) || "" });
972
+ if (typeof prefixInput.on === "function") {
973
+ prefixInput.on("change", () => localStorage.setItem(prefixKey, String(prefixInput.value || "")));
974
+ suffixInput.on("change", () => localStorage.setItem(suffixKey, String(suffixInput.value || "")));
975
+ }
976
+ appendRow(pcui, container, "上传目录", prefixInput);
977
+ appendRow(pcui, container, "文件后缀", suffixInput);
978
+ const pathLabel = new pcui.Label({ text: localStorage.getItem(`pcbridge:builder:${id}:url`) || "" });
979
+ appendRow(pcui, container, "引用路径", pathLabel);
980
+ const buildButton = new pcui.Button({ text: "构建并上传到 S3" });
981
+ const copyButton = new pcui.Button({ text: "复制引用路径" });
982
+ const logLabel = new pcui.Label({ text: "从项目 .env 或工作区 .env 读取 S3 配置" });
983
+ copyButton.on("click", () => {
984
+ if (pathLabel.text) void navigator.clipboard.writeText(pathLabel.text);
985
+ });
986
+ buildButton.on("click", async () => {
987
+ buildButton.enabled = false;
988
+ try {
989
+ let job = await daemonRequest("/builder/jobs", "POST", {
990
+ templateAssetId: id,
991
+ suffix: String(suffixInput.value || ""),
992
+ prefix: String(prefixInput.value || "")
993
+ });
994
+ while (job && job.state !== "completed" && job.state !== "error") {
995
+ logLabel.text = job.message || job.state;
996
+ await new Promise((resolve) => setTimeout(resolve, 1000));
997
+ job = await daemonRequest(
998
+ "/builder/jobs/" + encodeURIComponent(job.id),
999
+ "GET",
1000
+ {},
1001
+ 30000
1002
+ );
1003
+ }
1004
+ if (!job || job.state === "error") {
1005
+ throw new Error((job && job.error) || "Template build failed.");
1006
+ }
1007
+ pathLabel.text = job.publicUrl || "";
1008
+ localStorage.setItem(`pcbridge:builder:${id}:url`, pathLabel.text);
1009
+ logLabel.text = job.message || "上传完成";
1010
+ } catch (error) {
1011
+ logLabel.text = "构建失败: " + String((error && error.message) || error);
1012
+ } finally {
1013
+ buildButton.enabled = true;
1014
+ }
1015
+ });
1016
+ container.append(buildButton);
1017
+ container.append(copyButton);
1018
+ container.append(logLabel);
1019
+ layout.append(container);
1020
+ builderPanel = container;
1021
+ selectedTemplateId = id;
1022
+ selectedTemplateAsset = asset;
1023
+ }
1024
+
1025
+ function scheduleBuilderPanelRefresh(asset) {
1026
+ if (builderRefreshTimer !== null) clearTimeout(builderRefreshTimer);
1027
+ builderRefreshTimer = setTimeout(() => {
1028
+ builderRefreshTimer = null;
1029
+ const selection = selectedAssetStateFromEditor();
1030
+ if (selection.known) showBuilderPanel(selection.asset);
1031
+ else showBuilderPanel(asset || selectedTemplateAsset);
1032
+ }, 150);
1033
+ }
1034
+
1035
+ function installBuilderPanel() {
1036
+ if (!location.pathname.startsWith("/editor") || typeof setInterval !== "function") return;
1037
+ let subscribed = false;
1038
+ setInterval(() => {
1039
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) return;
1040
+ if (!subscribed) {
1041
+ subscribed = true;
1042
+ const refresh = (asset) => scheduleBuilderPanelRefresh(asset);
1043
+ const legacy = window.editor.selection;
1044
+ if (legacy && typeof legacy.on === "function") {
1045
+ legacy.on("add", refresh);
1046
+ legacy.on("remove", () => refresh());
1047
+ }
1048
+ const selection = window.editor.api.globals.selection;
1049
+ if (selection && typeof selection.on === "function") {
1050
+ selection.on("add", refresh);
1051
+ selection.on("remove", () => refresh());
1052
+ selection.on("change", () => refresh());
1053
+ }
1054
+ }
1055
+ const selection = selectedAssetStateFromEditor();
1056
+ if (selection.known) showBuilderPanel(selection.asset);
1057
+ else if (selectedTemplateAsset) showBuilderPanel(selectedTemplateAsset);
1058
+ }, 1000);
1059
+ }
1060
+
700
1061
  async function evalInPage(params, requestId) {
701
1062
  const timeoutMs = Number(params.timeoutMs || 15000);
702
1063
  const command = {
@@ -985,8 +1346,11 @@
985
1346
  if (method === "bridge:uploadAsset") return uploadAsset(params || {});
986
1347
  if (method === "bridge:focusViewport") return focusViewport(params || {});
987
1348
  if (method === "bridge:workspaceSnapshot") return workspaceSnapshot();
1349
+ if (method === "bridge:collectTemplateDependencies") return collectTemplateDependencies(params || {});
988
1350
  if (method === "bridge:readAssetText") return readAssetText(params || {});
989
1351
  if (method === "bridge:readAssetFile") return readAssetFile(params || {});
1352
+ if (method === "bridge:readAssetResource") return readAssetResource(params || {});
1353
+ if (method === "bridge:writeAssetFile") return writeAssetFile(params || {});
990
1354
  if (method === "bridge:writeScriptText") return writeScriptText(params || {});
991
1355
  throw new Error(`Unknown bridge method: ${method}`);
992
1356
  }
@@ -995,6 +1359,15 @@
995
1359
  if (event.source !== window) return;
996
1360
  const message = event.data;
997
1361
  if (!message || message.channel !== CHANNEL || message.side !== "isolated") return;
1362
+ if (message.type === "daemon-response" && message.id) {
1363
+ const waiter = daemonWaiters.get(message.id);
1364
+ if (!waiter) return;
1365
+ daemonWaiters.delete(message.id);
1366
+ clearTimeout(waiter.timer);
1367
+ if (message.ok) waiter.resolve(message.data);
1368
+ else waiter.reject(message.error || new Error("Local daemon request failed."));
1369
+ return;
1370
+ }
998
1371
  if (message.type !== "request") return;
999
1372
 
1000
1373
  const startedAt = performance.now();
@@ -1027,5 +1400,6 @@
1027
1400
  }
1028
1401
  });
1029
1402
 
1403
+ installBuilderPanel();
1030
1404
  window.postMessage({ channel: CHANNEL, side: "main", type: "ready" }, "*");
1031
1405
  })();
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "name": "PlayCanvas Agent Bridge",
4
4
  "description": "Connects open PlayCanvas Editor and Launch tabs to the local pcbridge daemon.",
5
- "version": "0.4.2",
5
+ "version": "0.5.0",
6
6
  "permissions": ["activeTab", "storage"],
7
7
  "host_permissions": [
8
8
  "http://playcanvas.com/*",
@@ -83,27 +83,11 @@ async function switchFrontend(active, url, custom, projectId) {
83
83
  window.close();
84
84
  }
85
85
 
86
- async function main() {
87
- const [active] = await chrome.tabs.query({ active: true, currentWindow: true });
88
- const url = active && active.url ? new URL(active.url) : null;
89
- const isEditor = isEditorUrl(url);
90
- const isLaunch = Boolean(url && url.hostname === "launch.playcanvas.com");
91
- const customMode = Boolean(isEditor && url.searchParams.has("use_local_frontend"));
92
- const config = await loadConfig();
93
- const status = await loadStatus(config, active && active.id);
86
+ function renderStatus(status, context) {
87
+ const { isEditor, isLaunch, customMode, rememberedMode } = context;
94
88
  const target = status && status.target;
95
89
  const workspace = status && status.workspace;
96
90
  const frontend = status && status.frontend;
97
- const projectId = (target && target.projectId) || projectIdFromUrl(url);
98
- const frontendPreference = isEditor
99
- ? await sendRuntimeMessage({
100
- type: "pcbridge:getFrontendPreference",
101
- tabId: active && active.id,
102
- url: url && url.toString(),
103
- projectId
104
- })
105
- : null;
106
- const rememberedMode = frontendPreference && frontendPreference.mode;
107
91
 
108
92
  const overallStatus = document.getElementById("overall-status");
109
93
  const daemonStatus = document.getElementById("daemon-status");
@@ -149,6 +133,7 @@ async function main() {
149
133
  syncing: ["Syncing", "warning"],
150
134
  synced: ["Synced", "success"],
151
135
  "local-change": ["Local changes", "warning"],
136
+ "remote-change": ["Remote changes", "warning"],
152
137
  conflict: ["Conflict", "danger"],
153
138
  error: ["Sync error", "danger"],
154
139
  unavailable: ["Unavailable", "neutral"]
@@ -167,7 +152,25 @@ async function main() {
167
152
  document.getElementById("metric-assets").textContent = String(counts.assets || 0);
168
153
  document.getElementById("metric-lazy").textContent = String(counts.lazyAssets || 0);
169
154
  document.getElementById("metric-conflicts").textContent = String(counts.conflicts || 0);
170
- workspaceNote.textContent = workspace.lastError || relativeTime(workspace.lastSyncedAt);
155
+ const phaseLabels = {
156
+ snapshot: "Reading asset snapshot",
157
+ reconciling: "Comparing workspace files",
158
+ persisting: "Saving project catalog"
159
+ };
160
+ const progress = workspace.progress;
161
+ const actionLabels = {
162
+ comparing: "checking",
163
+ downloading: "downloading",
164
+ uploading: "uploading",
165
+ conflict: "saving conflict"
166
+ };
167
+ const progressText = progress && progress.phase === "reconciling" && Number.isFinite(progress.total)
168
+ ? `${phaseLabels.reconciling} ${progress.completed || 0}/${progress.total || 0}` +
169
+ (progress.assetId ? ` · ${actionLabels[progress.action] || "checking"} #${progress.assetId}` : "")
170
+ : progress && phaseLabels[progress.phase];
171
+ workspaceNote.textContent = workspace.lastError || workspace.lastWarning ||
172
+ progressText ||
173
+ relativeTime(workspace.lastSyncedAt);
171
174
  workspaceNote.classList.toggle("error", Boolean(workspace.lastError));
172
175
  } else {
173
176
  workspacePath.textContent = workspace && workspace.rootDirectory
@@ -197,6 +200,36 @@ async function main() {
197
200
 
198
201
  useCustom.disabled = !isEditor || !serverReady || rememberedMode === "custom" || (!rememberedMode && customMode);
199
202
  useOfficial.disabled = !isEditor || rememberedMode === "official" || (!rememberedMode && !customMode);
203
+ }
204
+
205
+ async function main() {
206
+ const [active] = await chrome.tabs.query({ active: true, currentWindow: true });
207
+ const url = active && active.url ? new URL(active.url) : null;
208
+ const isEditor = isEditorUrl(url);
209
+ const isLaunch = Boolean(url && url.hostname === "launch.playcanvas.com");
210
+ const customMode = Boolean(isEditor && url.searchParams.has("use_local_frontend"));
211
+ const config = await loadConfig();
212
+ let status = await loadStatus(config, active && active.id);
213
+ let projectId = (status && status.target && status.target.projectId) || projectIdFromUrl(url);
214
+ const frontendPreference = isEditor
215
+ ? await sendRuntimeMessage({
216
+ type: "pcbridge:getFrontendPreference",
217
+ tabId: active && active.id,
218
+ url: url && url.toString(),
219
+ projectId
220
+ })
221
+ : null;
222
+ const context = {
223
+ isEditor,
224
+ isLaunch,
225
+ customMode,
226
+ rememberedMode: frontendPreference && frontendPreference.mode
227
+ };
228
+ renderStatus(status, context);
229
+
230
+ const copyPath = document.getElementById("copy-path");
231
+ const useCustom = document.getElementById("use-custom");
232
+ const useOfficial = document.getElementById("use-official");
200
233
  useCustom.addEventListener("click", () => switchFrontend(active, url, true, projectId));
201
234
  useOfficial.addEventListener("click", () => switchFrontend(active, url, false, projectId));
202
235
  copyPath.addEventListener("click", async () => {
@@ -206,6 +239,12 @@ async function main() {
206
239
  copyPath.textContent = "Copied";
207
240
  setTimeout(() => { copyPath.textContent = "Copy"; }, 1000);
208
241
  });
242
+
243
+ setInterval(async () => {
244
+ status = await loadStatus(config, active && active.id);
245
+ projectId = (status && status.target && status.target.projectId) || projectIdFromUrl(url);
246
+ renderStatus(status, context);
247
+ }, 1000);
209
248
  }
210
249
 
211
250
  main().catch((error) => {
@@ -168,6 +168,64 @@ async function loadConfig() {
168
168
  };
169
169
  }
170
170
 
171
+ async function requestDaemon(message, sender) {
172
+ const path = String(message.path || "");
173
+ const method = String(message.method || "GET").toUpperCase();
174
+ const allowed =
175
+ (path === "/builder/jobs" && method === "POST") ||
176
+ (/^\/builder\/jobs\/[^/]+$/.test(path) && method === "GET");
177
+ if (!allowed) {
178
+ return {
179
+ ok: false,
180
+ error: { code: "UNSUPPORTED_DAEMON_REQUEST", message: "Unsupported pcbridge browser request." }
181
+ };
182
+ }
183
+
184
+ const config = await loadConfig();
185
+ if (!config.token) {
186
+ return {
187
+ ok: false,
188
+ error: { code: "DAEMON_CONFIG_UNAVAILABLE", message: "pcbridge daemon configuration is unavailable." }
189
+ };
190
+ }
191
+ const payload = message.body && typeof message.body === "object" ? { ...message.body } : {};
192
+ const tabId = sender.tab && sender.tab.id;
193
+ if (method === "POST" && !payload.target && Number.isInteger(tabId)) {
194
+ payload.target = "tab:" + tabId;
195
+ }
196
+ const host = config.host || "127.0.0.1";
197
+ const port = config.port || 17329;
198
+ try {
199
+ const response = await fetch(`http://${host}:${port}${path}`, {
200
+ method,
201
+ headers: {
202
+ "Content-Type": "application/json",
203
+ "X-PCBridge-Token": config.token
204
+ },
205
+ body: method === "POST" ? JSON.stringify(payload) : undefined
206
+ });
207
+ const envelope = await response.json().catch(() => null);
208
+ if (!response.ok || !envelope || !envelope.ok) {
209
+ return {
210
+ ok: false,
211
+ error: (envelope && envelope.error) || {
212
+ code: "DAEMON_HTTP_ERROR",
213
+ message: `pcbridge daemon request failed with HTTP ${response.status}.`
214
+ }
215
+ };
216
+ }
217
+ return { ok: true, data: envelope.data };
218
+ } catch (error) {
219
+ return {
220
+ ok: false,
221
+ error: {
222
+ code: "DAEMON_UNREACHABLE",
223
+ message: String((error && error.message) || error)
224
+ }
225
+ };
226
+ }
227
+ }
228
+
171
229
  async function focusSenderTab(sender) {
172
230
  const tabId = sender.tab && sender.tab.id;
173
231
  const windowId = sender.tab && sender.tab.windowId;
@@ -221,6 +279,11 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
221
279
  return true;
222
280
  }
223
281
 
282
+ if (message && message.type === "pcbridge:daemonRequest") {
283
+ requestDaemon(message, sender).then(sendResponse);
284
+ return true;
285
+ }
286
+
224
287
  if (message && message.type === "pcbridge:getFrontendPreference") {
225
288
  getFrontendPreference({
226
289
  url: message.url || (sender.tab && sender.tab.url),