|
#!/usr/bin/env node |
|
// Universal-ish OpenCode Desktop project icon persistence/display workaround. |
|
// |
|
// What this patches: |
|
// 1. Renderer project enrichment: propagates persisted projectMeta.icon.override into project.icon.override |
|
// for all matching `childStore.icon -> base2.icon` blocks, including hashed bundle names. |
|
// 2. Edit Project dialog: loads persisted `workspace:icon` / `workspace:project.icon.override` |
|
// so the preview does not appear empty after restart/update. |
|
// |
|
// Usage after OpenCode Desktop update: |
|
// node C:\Users\zail\patch-opencode-icons.mjs |
|
// Optional explicit resources dir: |
|
// node C:\Users\zail\patch-opencode-icons.mjs "C:\Users\zail\AppData\Local\Programs\OpenCode\resources" |
|
// |
|
// The script creates a timestamped app.asar backup next to app.asar before changing anything. |
|
|
|
import fs from "node:fs"; |
|
import path from "node:path"; |
|
import { execFileSync } from "node:child_process"; |
|
|
|
const defaultResources = path.join( |
|
process.env.LOCALAPPDATA || path.join(process.env.USERPROFILE || "", "AppData", "Local"), |
|
"Programs", |
|
"OpenCode", |
|
"resources", |
|
); |
|
|
|
const resourcesDir = process.argv[2] ? path.resolve(process.argv[2]) : defaultResources; |
|
const appAsar = path.join(resourcesDir, "app.asar"); |
|
const patchedAsar = path.join(resourcesDir, "app.asar.patched"); |
|
const workDir = path.join(process.env.TEMP || resourcesDir, `opencode-icon-patch-${Date.now()}`); |
|
const PATCH_MARKER = "opencode-icon-patch-v2"; |
|
|
|
function log(message) { |
|
console.log(`[opencode-icon-patch] ${message}`); |
|
} |
|
|
|
function fail(message) { |
|
console.error(`[opencode-icon-patch] ${message}`); |
|
process.exit(1); |
|
} |
|
|
|
function run(command, args) { |
|
execFileSync(command, args, { stdio: "inherit", shell: process.platform === "win32" }); |
|
} |
|
|
|
const npx = process.platform === "win32" ? "npx.cmd" : "npx"; |
|
|
|
function readText(file) { |
|
return fs.readFileSync(file, "utf8"); |
|
} |
|
|
|
function writeText(file, text) { |
|
fs.writeFileSync(file, text, "utf8"); |
|
} |
|
|
|
function replaceOnceExact(file, oldText, newText, label) { |
|
const input = readText(file); |
|
if (input.includes(newText)) { |
|
log(`${label}: already patched`); |
|
return; |
|
} |
|
if (!input.includes(oldText)) fail(`${label}: target snippet not found. OpenCode changed its bundle; patch needs updating.`); |
|
writeText(file, input.replace(oldText, newText)); |
|
log(`${label}: patched`); |
|
} |
|
|
|
function replaceRegex(file, regex, replacer, label) { |
|
const input = readText(file); |
|
const output = input.replace(regex, replacer); |
|
if (output === input) { |
|
log(`${label}: no matching unpatched block found`); |
|
return 0; |
|
} |
|
writeText(file, output); |
|
const count = (input.match(regex) || []).length; |
|
log(`${label}: patched ${count} occurrence(s)`); |
|
return count; |
|
} |
|
|
|
function findFile(dir, predicate) { |
|
const stack = [dir]; |
|
while (stack.length) { |
|
const current = stack.pop(); |
|
for (const entry of fs.readdirSync(current, { withFileTypes: true })) { |
|
const full = path.join(current, entry.name); |
|
if (entry.isDirectory()) stack.push(full); |
|
else if (predicate(full, entry.name)) return full; |
|
} |
|
} |
|
return undefined; |
|
} |
|
|
|
if (!fs.existsSync(appAsar)) fail(`app.asar not found: ${appAsar}`); |
|
|
|
const backup = path.join(resourcesDir, `app.asar.backup-icons-${new Date().toISOString().replace(/[:.]/g, "-")}`); |
|
fs.copyFileSync(appAsar, backup); |
|
log(`backup created: ${backup}`); |
|
|
|
fs.rmSync(workDir, { recursive: true, force: true }); |
|
fs.mkdirSync(workDir, { recursive: true }); |
|
|
|
run(npx, ["--yes", "asar", "extract", appAsar, workDir]); |
|
|
|
const assetsDir = path.join(workDir, "out", "renderer", "assets"); |
|
if (!fs.existsSync(assetsDir)) fail(`renderer assets directory not found: ${assetsDir}`); |
|
|
|
const mainBundle = findFile(assetsDir, (full, name) => { |
|
if (!/^main-.*\.js$/.test(name)) return false; |
|
const text = readText(full); |
|
return text.includes("projectMeta") && text.includes("childStore.icon") && text.includes("base2.icon"); |
|
}); |
|
|
|
const dialogBundle = findFile(assetsDir, (full, name) => { |
|
if (!/^dialog-edit-project-.*\.js$/.test(name)) return false; |
|
const text = readText(full); |
|
return text.includes("function DialogEditProject") && text.includes("iconOverride"); |
|
}); |
|
|
|
if (!mainBundle) fail("main renderer bundle not found"); |
|
if (!dialogBundle) fail("edit project dialog bundle not found"); |
|
|
|
log(`main bundle: ${path.relative(workDir, mainBundle)}`); |
|
log(`dialog bundle: ${path.relative(workDir, dialogBundle)}`); |
|
|
|
replaceRegex( |
|
mainBundle, |
|
/^([ \t]*)if \(childStore\.icon(?: \|\| base2\.icon\?\.override)?\) \{\r?\n\1 return \{\r?\n\1 \.\.\.base2,\r?\n\1 icon: \{\r?\n\1 \.\.\.base2\.icon,\r?\n\1 override: childStore\.icon(?: \|\| base2\.icon\?\.override)?\r?\n\1 \}\r?\n\1 \};\r?\n\1\}/gm, |
|
(_match, indent) => `${indent}const projectMetaIcon = childStore.projectMeta?.icon?.override; |
|
${indent}if (childStore.icon || base2.icon?.override || projectMetaIcon) { |
|
${indent} return { |
|
${indent} ...base2, |
|
${indent} icon: { |
|
${indent} ...childStore.projectMeta?.icon, |
|
${indent} ...base2.icon, |
|
${indent} override: childStore.icon || base2.icon?.override || projectMetaIcon |
|
${indent} } |
|
${indent} }; |
|
${indent}}`, |
|
"project metadata icon propagation", |
|
); |
|
|
|
if (readText(dialogBundle).includes("function ocIconWorkspaceStorage")) { |
|
log("edit dialog workspace storage helpers: already patched"); |
|
} else { |
|
replaceOnceExact( |
|
dialogBundle, |
|
`const AVATAR_COLOR_KEYS = ["pink", "mint", "orange", "purple", "cyan", "lime"]; |
|
function DialogEditProject(props) {`, |
|
`const AVATAR_COLOR_KEYS = ["pink", "mint", "orange", "purple", "cyan", "lime"]; |
|
// ${PATCH_MARKER}: helpers for persisted project icon preview across hashed OpenCode bundles. |
|
function ocIconChecksum(content) { |
|
if (!content) return void 0; |
|
let hash = 2166136261; |
|
for (let i = 0; i < content.length; i++) { |
|
hash ^= content.charCodeAt(i); |
|
hash = Math.imul(hash, 16777619); |
|
} |
|
return (hash >>> 0).toString(36); |
|
} |
|
function ocIconTrimTrailingSlashes(value) { |
|
for (let i = value.length - 1; i >= 0; i--) { |
|
if (value[i] !== "/") return value.slice(0, i + 1); |
|
} |
|
return ""; |
|
} |
|
function ocIconIsDrive(value) { |
|
if (value.length !== 2) return false; |
|
const code = value.charCodeAt(0); |
|
return value[1] === ":" && (code >= 65 && code <= 90 || code >= 97 && code <= 122); |
|
} |
|
function ocIconPathKey(path) { |
|
const value = path[1] === ":" || path.startsWith("\\\\") ? path.replaceAll("\\\\", "/") : path; |
|
const trimmed = ocIconTrimTrailingSlashes(value); |
|
if (!trimmed && value.startsWith("/")) return "/"; |
|
if (ocIconIsDrive(trimmed)) return trimmed + "/"; |
|
return trimmed; |
|
} |
|
function ocIconWorkspaceStorage(dir) { |
|
const head = (dir.slice(0, 12) || "workspace").replace(/[^a-zA-Z0-9._-]/g, "-"); |
|
const sum = ocIconChecksum(dir) ?? "0"; |
|
return "opencode.workspace." + head + "." + sum + ".dat"; |
|
} |
|
function ocIconReadValue(raw) { |
|
if (!raw) return void 0; |
|
if (typeof raw === "string" && raw.startsWith("data:image/")) return raw; |
|
const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; |
|
if (typeof parsed === "string" && parsed.startsWith("data:image/")) return parsed; |
|
return parsed?.value; |
|
} |
|
function DialogEditProject(props) {`, |
|
"edit dialog workspace storage helpers", |
|
); |
|
} |
|
|
|
if (readText(dialogBundle).includes("const loadStoredIcon = async () =>")) { |
|
log("edit dialog stored icon preview loader: already patched"); |
|
} else { |
|
replaceOnceExact( |
|
dialogBundle, |
|
` const [store, setStore] = createStore({ |
|
name: defaultName(), |
|
color: props.project.icon?.color, |
|
iconOverride: props.project.icon?.override, |
|
startup: props.project.commands?.start ?? "", |
|
dragOver: false, |
|
iconHover: false |
|
});`, |
|
` const [store, setStore] = createStore({ |
|
name: defaultName(), |
|
color: props.project.icon?.color, |
|
iconOverride: props.project.icon?.override, |
|
startup: props.project.commands?.start ?? "", |
|
dragOver: false, |
|
iconHover: false |
|
}); |
|
const loadStoredIcon = async () => { |
|
const storageName = ocIconWorkspaceStorage(ocIconPathKey(props.project.worktree)); |
|
const iconRaw = await window.api?.storeGet?.(storageName, "workspace:icon"); |
|
const iconValue = ocIconReadValue(iconRaw); |
|
if (iconValue) { |
|
setStore("iconOverride", iconValue); |
|
return; |
|
} |
|
const projectRaw = await window.api?.storeGet?.(storageName, "workspace:project"); |
|
const project = typeof projectRaw === "string" ? JSON.parse(projectRaw) : projectRaw; |
|
const projectIcon = project?.value?.icon?.override; |
|
if (projectIcon) setStore("iconOverride", projectIcon); |
|
}; |
|
void loadStoredIcon().catch(() => void 0);`, |
|
"edit dialog stored icon preview loader", |
|
); |
|
} |
|
|
|
const mainTextAfter = readText(mainBundle); |
|
const unpatchedIconBlocks = (mainTextAfter.match(/^([ \t]*)if \(childStore\.icon\) \{\r?\n\1 return \{\r?\n\1 \.\.\.base2,\r?\n\1 icon: \{\r?\n\1 \.\.\.base2\.icon,\r?\n\1 override: childStore\.icon\r?\n\1 \}\r?\n\1 \};\r?\n\1\}/gm) || []).length; |
|
const projectMetaIconBlocks = (mainTextAfter.match(/const projectMetaIcon = childStore\.projectMeta\?\.icon\?\.override;/g) || []).length; |
|
if (unpatchedIconBlocks > 0) fail(`verification failed: ${unpatchedIconBlocks} unpatched childStore.icon block(s) remain`); |
|
if (projectMetaIconBlocks < 1) fail(`verification failed: projectMetaIcon propagation block missing`); |
|
|
|
const dialogTextAfter = readText(dialogBundle); |
|
if (!dialogTextAfter.includes("function ocIconWorkspaceStorage")) fail("verification failed: dialog storage helpers missing"); |
|
if (!dialogTextAfter.includes("loadStoredIcon")) fail("verification failed: dialog stored icon loader missing"); |
|
log(`verification passed: ${projectMetaIconBlocks} projectMetaIcon propagation block(s), dialog loader present`); |
|
|
|
fs.rmSync(patchedAsar, { force: true }); |
|
run(npx, ["--yes", "asar", "pack", workDir, patchedAsar]); |
|
fs.rmSync(workDir, { recursive: true, force: true }); |
|
|
|
try { |
|
fs.copyFileSync(patchedAsar, appAsar); |
|
fs.rmSync(patchedAsar, { force: true }); |
|
log("patched app.asar successfully"); |
|
log("restart OpenCode Desktop when convenient"); |
|
} catch (error) { |
|
const applyScript = path.join(resourcesDir, "apply-patched-asar.ps1"); |
|
fs.writeFileSync( |
|
applyScript, |
|
`$ErrorActionPreference = "Stop"\n` + |
|
`$resources = ${JSON.stringify(resourcesDir)}\n` + |
|
`$app = Join-Path $resources "app.asar"\n` + |
|
`$patched = Join-Path $resources "app.asar.patched"\n` + |
|
`if (-not (Test-Path -LiteralPath $patched)) { throw "Patched file not found: $patched" }\n` + |
|
`Copy-Item -LiteralPath $patched -Destination $app -Force\n` + |
|
`Remove-Item -LiteralPath $patched -Force\n` + |
|
`"Patched app.asar applied successfully"\n`, |
|
"utf8", |
|
); |
|
log(`could not replace app.asar now: ${error.message}`); |
|
log(`patched file kept at: ${patchedAsar}`); |
|
log(`after closing OpenCode, run: powershell -ExecutionPolicy Bypass -File "${applyScript}"`); |
|
} |