v2.2.2

cherry-electron-dev

cherryhq@cherryhq⭐ 53.5k stars· last commit 8h ago· 1772 open issues

Develop, fix, profile, and test PRs in a tracked Cherry Studio Electron instance. Use for implementation, UI and interaction work, runtime debugging, DevTools inspection, performance analysis, and interactive PR verification with a test report. Reuse a verified workspace instance and manage its lifetime according to the selected workflow.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

7.0/10
Verified
Oct 8, 2026

// RATINGS

⭐GitHub Stars
⭐⭐⭐⭐⭐ 53.5k on GitHubGitHub ↗

Very popular

🟢ProSkills ScoreAI Verified
7.0/10
📍

Not yet listed on ClawHub or SkillsMP

// README

[![][deepwiki-shield]][deepwiki-link] [![][twitter-shield]][twitter-link] [![][discord-shield]][discord-link] [![][telegram-shield]][telegram-link]

[![][github-release-shield]][github-release-link] [![][github-nightly-shield]][github-nightly-link] [![][github-contributors-shield]][github-contributors-link] [![][license-shield]][license-link] [![][commercial-shield]][commercial-link] [![][sponsor-shield]][sponsor-link]

🍒 Cherry Studio

Cherry Studio is an AI workstation for Windows, macOS, and Linux. Chat with multiple models, work with agents, build knowledge bases, create images, and automate everyday tasks in one place.

Download Desktop · Getting Started

📱 Cherry Studio Mobile is now available for iOS and Android! Download · GitHub repository.

👏 Join Telegram Group|Discord | QQ Group(575014769)

❤️ Like Cherry Studio? Give it a star 🌟 or Sponsor to support the development!

🌠 Screenshots

Agents — work with files, tools, and multi-step tasks.

Cherry Studio agent workspace creating a presentation

Conversations — explore ideas with your models and assistants.

Cherry Studio conversation displaying a Mermaid chart

Model providers — configure services, API keys, and models in one place.

Cherry Studio model provider settings in light mode

Knowledge bases — organize sources for retrieval and agent workflows.

Cherry Studio knowledge base with folders and documents

Image creation — turn prompts into images and refine your work.

Cherry Studio image creation workspace

🌟 Key Features

Agents & Automation

  • 🤖 Create agents with their own instructions, workspaces, models, and tool permissions.
  • 🛠️ Work with files, run commands, and use browser and computer automation tools.
  • 🔌 Extend capabilities with Skills and MCP (Model Context Protocol) servers.
  • ⏰ Run scheduled tasks and connect agents to messaging platforms through Channels.

Models & Conversations

  • ☁️ Connect OpenAI, Anthropic, Gemini, and other cloud providers, or add custom compatible services.
  • 💻 Use local models through Ollama and LM Studio.
  • 💬 Customize assistants and compare responses from multiple models in one conversation.
  • 📝 Read and share rich responses with Markdown, code highlighting, formulas, Mermaid charts, and conversation exports.

Knowledge & Documents

  • 📚 Build local knowledge bases from files, folders, and web pages, then use them in conversations and agents.
  • 📄 Process PDF, Office documents, images, and text, with OCR and document processing options.
  • ✍️ Organize ideas in Markdown notes and manage attachments and generated files in the file library.

Creative & Everyday Tools

  • 🎨 Generate and edit images with supported image models.
  • 🔤 Translate text and documents, and use quick translation from other apps.
  • 🔍 Search the web, read pages, and find content across your conversations and knowledge bases.
  • 🧩 Open web-based tools through Mini Apps, or use the API Gateway to connect other applications to your configured models.

Voice & Workspace

  • 🎙️ Dictate messages and listen to responses with speech recognition and text-to-speech options, including local models.
  • 🪟 Work across tabs and detached windows, with window pinning, Quick Assistant, and text selection tools.
  • 🌈 Customize your workspace with light and dark themes, layouts, and custom CSS.
  • 💾 Keep conversation history and knowledge bases on your device, with local and WebDAV backup options.

Model and tool availability depends on your provider, operating system, and configuration. Some features require API credentials, downloaded models, additional dependencies, or system permissions. See the user documentation for setup.

📝 Roadmap

Follow upcoming work on our project board and GitHub Issues. See Releases for features and fixes already shipped.

Share ideas and discuss priorities in GitHub Discussions.

🌈 Theme

Check each community theme's supported Cherry Studio version before installing. Themes written for v1 need adaptation for the v2 interface.

Contributions of compatible themes are welcome.

🤝 Contributing

Contributions of code, bug reports, documentation, translations, product ideas, and community support are welcome. Browse good first issues to find a place to start.

Getting Started

  1. Read the Contributing Guide and Development Guide.
  2. Fork the repository and create a focused branch from main.
  3. Validate your changes, sign and sign off your commits, and open a pull request targeting main using the repository template.

See the Branching Strategy for branch and release conventions.

🏢 Enterprise Edition

Cherry Studio Enterprise Edition brings centralized model management, shared knowledge bases, employee access controls, and private deployment options to teams and organizations.

Visit the Enterprise website for current capabilities and deployment information. For purchasing, pricing, or a demo, contact [email protected].

🔗 Related Projects

// HOW IT'S BUILT

// FILES

5 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • .agents/skills/cherry-electron-dev/SKILL.md3.3 KB9eb7412a0f81upstream ↗
    ---
    name: cherry-electron-dev
    description: Develop, fix, profile, and test PRs in a tracked Cherry Studio Electron instance. Use for implementation, UI and interaction work, runtime debugging, DevTools inspection, performance analysis, and interactive PR verification with a test report. Reuse a verified workspace instance and manage its lifetime according to the selected workflow.
    ---
    
    # Cherry Studio Development
    
    ## Choose the workflow
    
    - For ongoing implementation, debugging, or profiling in the current checkout,
      follow the development loop below with the `persistent` runtime policy.
    - For a bounded PR test, read [PR Testing](references/pr-testing.md) and follow
      that workflow with the `ephemeral` runtime policy. It covers PR checkout,
      interactive tests, reporting, cleanup, and restoration of the original branch.
    - For code review without interactive app testing, use `gh-pr-review`.
    
    ## Required runtime workflow
    
    Before reading or controlling Electron UI, read
    [Electron Instance Management](references/electron-instance.md) and select the
    policy for the chosen workflow. Preserve a borrowed instance's existing policy
    and ownership.
    
    That reference is the only authority for instance discovery, `instance.json`,
    CDP target selection, launching, replacement, shutdown, and troubleshooting.
    Do not reproduce those procedures here or substitute generic Electron app
    control.
    
    ## Development loop
    
    1. State the requested behavior and the evidence that will prove it.
    2. Read the relevant code and nearby README files.
    3. Verify and reuse the tracked instance through the runtime reference.
    4. Reproduce or inspect the current behavior before editing when practical.
    5. Capture the smallest useful evidence: UI state, DOM, console/network output,
       main-process logs, persisted state, or performance metrics.
    6. Trace the responsible code path and make only the requested change.
    7. Keep Electron running. Use HMR for renderer changes and verify in the same
       window.
    8. Repeat the same scenario and compare before/after evidence.
    
    Inspect the real window at the relevant size and theme for UI work. Check both
    renderer and main-process evidence for renderer failures.
    
    Restart only for a non-reloadable layer, crash, unreliable runtime state, or
    startup profiling. Use the reference's exact-instance replacement procedure,
    refresh `instance.json`, and keep the replacement running.
    
    Run the narrowest relevant validation and follow current user and repository
    instructions for lint, formatting, and tests.
    
    ## Performance and DevTools
    
    For lag, jank, high CPU, memory growth, leaks, slow startup, or explicit
    DevTools use, read
    [Performance Debugging](references/performance-debugging.md).
    
    Store temporary logs, screenshots, and profiles under
    `.context/cherry-electron-dev/`. Compare a quiet baseline with the same bounded
    scenario before and after a fix. Detach profiling sessions afterward; do not
    close the CDP browser, page, or Electron process.
    
    ## Development handoff
    
    Leave reused user-owned and healthy agent-launched instances running after the
    instruction. Stop one only when the user asks, a required restart is part of
    the task, or the instance is unhealthy and blocks progress.
    
    Report the verified PID, whether it remains running, CDP port, tracking file,
    evidence paths, reproduction, and verification.
    
  • .agents/skills/cherry-electron-dev/references/electron-instance.md7.9 KBfdf124cd030aupstream ↗
    # Electron Instance Management
    
    Use this as the single runtime procedure for development and PR testing in
    `cherry-electron-dev`.
    
    ## Contents
    
    - Session policy and scratch data
    - Verify or discover an instance
    - Bind CDP to the exact target
    - Gracefully replace an instance
    - Start and track a debug instance
    - Finish or recover
    - Troubleshooting
    
    ## Session policy and scratch data
    
    Choose the caller's policy before touching Electron:
    
    | Policy | Use | Finish |
    | --- | --- | --- |
    | `persistent` | Ongoing development | Leave a healthy instance running |
    | `ephemeral` | A bounded PR test | Stop only the instance started by this test |
    
    Treat pre-existing processes as user-owned. Preserve `userData`, databases,
    caches, and preferences unless the user explicitly requests a reset.
    
    Use `.context/cherry-electron-dev/` for runtime state and artifacts. The
    repository ignores this path, and `mkdir -p` creates it in Conductor and
    ordinary clones:
    
    ```bash
    mkdir -p .context/cherry-electron-dev
    ```
    
    Track the active instance in `.context/cherry-electron-dev/instance.json` with:
    
    - workspace path and Git HEAD at launch
    - `persistent` or `ephemeral` policy and `user` or `agent` ownership
    - `launch_purpose` (`development`, `pr-test:<number>`, or `external`)
    - `workflow_relation` (`started` or `borrowed`)
    - Electron PID, runner PID/session, and process group
    - CDP and main-process inspector ports
    - exact main-window target URL
    - development profile suffix
    - launch command, log path, and start time
    
    The file is a hint, not proof. Revalidate it before every UI operation.
    At the start of a new workflow, an already-running instance is `borrowed` even
    when the same agent launched it during an earlier instruction.
    
    ## Verify or discover an instance
    
    Reuse the record only when all checks pass:
    
    1. The Electron PID is alive.
    2. Its cwd is the exact current workspace.
    3. The recorded CDP listener belongs to that PID.
    4. `/json/list` contains the recorded Cherry Studio target.
    5. When exact checked-out code matters, the launch Git HEAD matches current
       HEAD; otherwise restart instead of relying on HMR for main-process changes.
    
    ```bash
    lsof -a -p <ELECTRON_PID> -d cwd -Fn
    lsof -nP -a -p <ELECTRON_PID> -iTCP:<CDP_PORT> -sTCP:LISTEN
    curl -fsS http://127.0.0.1:<CDP_PORT>/json/version | jq .
    curl -fsS http://127.0.0.1:<CDP_PORT>/json/list | \
      jq '.[] | {id, type, title, url}'
    ```
    
    If the record is missing or stale, discover before launching:
    
    ```bash
    ps -axo pid=,ppid=,pgid=,command= | \
      rg -i 'Cherry Studio|CherryStudio|electron-vite|remote-debugging-port'
    lsof -nP -iTCP -sTCP:LISTEN | rg 'Electron|Cherry|:9222|:5173'
    lsof -a -p <ELECTRON_PID> -d cwd -Fn
    ps -o pid=,ppid=,pgid=,command= -p <PID>,<PARENT_PID>
    ```
    
    Ignore candidates that cannot be tied to this workspace. A packaged app and
    another checkout are not interchangeable. Never infer ownership from an open
    port alone.
    
    If a candidate passes every applicable check, adopt it immediately instead of
    launching:
    
    1. Attach to its verified CDP endpoint.
    2. Write or refresh `instance.json` with its live identity and
       `workflow_relation: borrowed`.
    3. Preserve a trustworthy existing policy and ownership. Without a trustworthy
       record, treat a pre-existing process as `user` owned and `persistent`.
    4. End the launch path. Start another instance only when no suitable candidate
       exists or replacement is required.
    
    ## Bind CDP to the exact target
    
    Use the verified CDP endpoint exclusively. List targets and match URL and
    title; never assume target index `0`. The normal main target is titled
    `Cherry Studio` and uses:
    
    ```text
    http://localhost:5173/windows/main/index.html
    ```
    
    If the dev server selects another port, require the same
    `/windows/main/index.html` path and record the exact URL. Re-list after windows
    open or close. Do not navigate a target unless navigation is part of the test.
    
    Use Playwright/CDP or optional `agent-browser`. Do not install a global CLI just
    for a task, and do not launch another instance because one controller is
    unavailable.
    
    Never pass `Electron`, `com.github.Electron`, or a `node_modules` Electron.app
    path to Computer Use or another app-control API. Shared Electron identifiers
    can launch or select the wrong checkout.
    
    ## Gracefully replace an instance
    
    Replace only when current-workspace code or required CDP access is unavailable.
    Before replacing a user-owned process, explain why and record its PID, command,
    cwd, parent/runner, PGID, and ports.
    
    Send `SIGTERM` to the exact Electron main PID and wait up to eight seconds:
    
    ```bash
    kill -TERM <ELECTRON_PID>
    for _ in $(seq 1 16); do
      kill -0 <ELECTRON_PID> 2>/dev/null || break
      sleep 0.5
    done
    kill -0 <ELECTRON_PID> 2>/dev/null && echo "still running"
    ```
    
    If Electron exits but its verified same-workspace runner remains, terminate
    that PID separately. Never use broad `pkill`, kill arbitrary port owners, or
    signal a process group before inspecting every member.
    
    Do not escalate automatically to `SIGKILL`. Report the remaining PID and logs
    and ask before forcing a process that may be migrating, backing up, or
    preventing quit. Verify the old PID and ports are gone before replacement.
    
    ## Start and track a debug instance
    
    Read `package.json` for the current debug command. If its default CDP or
    inspector port belongs to an unrelated process, choose free ports and change
    only those arguments; do not kill the owner.
    
    Prefer a managed terminal session. With a terminal tool such as
    `exec_command`, request a PTY and short initial yield, retain its returned
    session ID, and let this command continue:
    
    ```bash
    pnpm debug 2>&1 | tee .context/cherry-electron-dev/electron.log
    ```
    
    Do not run that command as an ordinary blocking call. If no managed-session
    tool exists, use a recorded background runner:
    
    ```bash
    nohup pnpm debug >.context/cherry-electron-dev/electron.log 2>&1 &
    echo $!
    ```
    
    Immediately record the returned runner PID. Resolve and record the real
    Electron PID and PGID after launch.
    
    Keep the existing development profile for `persistent` work. For an isolated
    PR test, set a distinct `CS_DEV_USER_DATA_SUFFIX` and record it.
    
    Wait for the selected CDP endpoint, then identify and record the exact target:
    
    ```bash
    for _ in $(seq 1 60); do
      curl -fsS http://127.0.0.1:<CDP_PORT>/json/version >/dev/null && break
      sleep 0.5
    done
    curl -fsS http://127.0.0.1:<CDP_PORT>/json/list | \
      jq '.[] | {id, type, title, url}'
    ```
    
    Write `instance.json` only after PID, cwd, listener ownership, and target checks
    pass. Give a new instance `workflow_relation: started`; never reclassify a
    borrowed instance as newly started.
    
    ## Finish or recover
    
    For `persistent`, leave healthy user-owned and agent-owned instances running.
    For `ephemeral`, stop an instance only when all of these are true:
    
    1. Its verified record has `workflow_relation: started`.
    2. Its verified record still says `ephemeral` and `agent` owned.
    3. Its PID, cwd, and launch purpose still match the current test.
    
    Leave every borrowed instance running, regardless of whether its existing
    ownership is `user` or `agent`.
    
    If an unexpected window or PID appears:
    
    1. Stop UI actions.
    2. Identify only the new PID by command and cwd.
    3. Gracefully stop that verified unexpected PID.
    4. Revalidate the tracked PID, cwd, CDP listener, and target.
    5. Resume only through the tracked CDP endpoint.
    
    Never close all Electron processes to recover from a targeting mistake.
    
    ## Troubleshooting
    
    | Symptom | Action |
    | --- | --- |
    | CDP works but the page is missing | Re-list targets and match URL/title; splash, migration, settings, detached tabs, and mini-apps are separate targets. |
    | Debug launch exits | Inspect the recorded log for a profile lock, native rebuild, database/startup failure, or port collision; confirm the old PID exited. |
    | Splash or migration is stuck | Read startup logs and wait; do not bypass, reset, or force-close without understanding its phase. |
    | CDP automation is unavailable | Use logs/source when sufficient. If UI evidence is essential, explain why and use the replacement procedure; never fall back to generic Electron control. |
    
  • .agents/skills/cherry-electron-dev/references/performance-debugging.md15 KB85581080e57fupstream ↗
    # Performance Debugging
    
    Use this reference for Cherry Studio lag, jank, CPU, memory, leak, startup, and
    DevTools investigations.
    
    ## Contents
    
    - Bind safely and choose a profile
    - Quick renderer metrics
    - Interaction trace
    - Memory and allocation
    - Development-runtime overhead
    - Node and main-process checks
    - Startup analysis
    - Interpretation and reporting
    
    ## Bind safely and choose a profile
    
    First read [Electron Instance Management](electron-instance.md) and complete
    its PID, workspace, CDP, and target checks. Never find or open a development
    instance through the macOS application name `Electron`.
    
    Connect Playwright to the recorded CDP port and exact main target:
    
    ```js
    var { chromium } = await import("playwright")
    var browser = await chromium.connectOverCDP("http://127.0.0.1:<CDP_PORT>")
    var page = browser
      .contexts()
      .flatMap((context) => context.pages())
      .find((candidate) => candidate.url() === "<MAIN_TARGET_URL>")
    if (!page || (await page.title()) !== "Cherry Studio") {
      throw new Error("Bound Cherry Studio main target not found")
    }
    var cdp = await page.context().newCDPSession(page)
    ```
    
    Never call `browser.close()`, `page.close()`, or an Electron quit action.
    Detach only the profiling `CDPSession`. For visible DevTools, open the selected
    target's frontend without replacing the bound session:
    
    ```text
    http://127.0.0.1:<CDP_PORT><devtoolsFrontendUrl>
    ```
    
    Choose the smallest profile:
    
    | Question | Profile |
    | --- | --- |
    | Renderer load or memory level? | Quick metrics |
    | Cause of a visible stall? | 5-30 second trace |
    | Memory growth after repetition? | Repeated checkpoints |
    | Allocation source? | Allocation sampling |
    | Main/helper resource use? | Process sampling, then Node inspector |
    | Slow startup? | Restart-aware startup analysis |
    
    Collect a quiet idle baseline. Keep action, duration, window size, route, data,
    and visible-DevTools state identical between comparisons.
    
    ## Quick renderer metrics
    
    ```js
    await cdp.send("Performance.enable")
    var beforeRaw = await cdp.send("Performance.getMetrics")
    var before = Object.fromEntries(
      beforeRaw.metrics.map(({ name, value }) => [name, value])
    )
    // Run one bounded scenario.
    var afterRaw = await cdp.send("Performance.getMetrics")
    var after = Object.fromEntries(
      afterRaw.metrics.map(({ name, value }) => [name, value])
    )
    ```
    
    Compare deltas for cumulative counters: `TaskDuration`, `ScriptDuration`,
    `LayoutDuration`, `LayoutCount`, `RecalcStyleDuration`, `RecalcStyleCount`, and
    `V8CompileDuration`. Treat `JSHeapUsedSize`, `JSHeapTotalSize`, `Nodes`,
    `Documents`, `Frames`, and `JSEventListeners` as point-in-time gauges.
    
    Approximate renderer main-thread utilization for a window of
    `elapsedSeconds`:
    
    ```text
    100 * delta(TaskDuration) / elapsedSeconds
    ```
    
    This is orientation, not complete CPU usage. Repeat identical scenarios and
    compare medians when differences are small.
    
    ## Interaction trace
    
    Trace one reproducible action for 5-30 seconds:
    
    ```js
    var traceDone = new Promise((resolve) =>
      cdp.once("Tracing.tracingComplete", resolve)
    )
    await cdp.send("Tracing.start", {
      categories: [
        "devtools.timeline",
        "v8",
        "blink.user_timing",
        "disabled-by-default-devtools.timeline"
      ].join(","),
      transferMode: "ReturnAsStream"
    })
    // Perform the action.
    await cdp.send("Tracing.end")
    var { stream } = await traceDone
    var chunks = []
    while (true) {
      var part = await cdp.send("IO.read", { handle: stream })
      chunks.push(Buffer.from(part.data, part.base64Encoded ? "base64" : "utf8"))
      if (part.eof) break
    }
    await cdp.send("IO.close", { handle: stream })
    var fs = await import("node:fs/promises")
    await fs.writeFile("<TRACE_PATH>.json", Buffer.concat(chunks))
    ```
    
    Correlate long tasks with script stacks, layout, paint, GC, and user timing.
    Keep raw traces under `.context`; they may contain private UI content or URLs.
    
    ## Memory and allocation
    
    For leak suspicion, record heap/nodes/documents/listeners at idle, repeat the
    same action a fixed number of times, return to the same idle state, and record
    again across multiple cycles. One larger heap value is not proof; V8 may defer
    GC. Do not force GC unless a post-GC comparison is explicitly needed.
    
    Triangulate renderer memory instead of relying on one number:
    
    - OS RSS or process footprint includes V8, native allocations, graphics, and
      diagnostic buffers.
    - `JSHeapUsedSize` covers only the live V8 heap.
    - `Nodes`, `Documents`, `Frames`, and `JSEventListeners` expose retained UI
      structures but not native or performance-entry storage.
    
    Large OS growth with a stable JS heap and stable DOM gauges is not, by itself,
    an application heap leak. Check development-runtime instrumentation before
    changing product code.
    
    For bounded allocation attribution:
    
    ```js
    await cdp.send("HeapProfiler.enable")
    await cdp.send("HeapProfiler.startSampling", { samplingInterval: 32768 })
    // Perform one bounded scenario.
    var { profile } = await cdp.send("HeapProfiler.stopSampling")
    var fs = await import("node:fs/promises")
    await fs.writeFile("<PROFILE_PATH>.json", JSON.stringify(profile))
    ```
    
    Use a full heap snapshot only when sampling and gauges are insufficient. Warn
    first: it can pause the renderer, be large, and contain private data.
    
    ## Development-runtime overhead
    
    Development measurements are useful for relative comparisons, but their
    absolute memory and CPU are not a production baseline. HMR, source maps,
    DevTools, Strict Mode, and framework instrumentation can add or retain work.
    Keep visible-DevTools state identical across samples and identify the retaining
    system before attributing growth to Cherry Studio.
    
    React 19 development builds emit component Performance Tracks through User
    Timing. When a changing prop contains a growing HTML or text string, React can
    serialize both previous and current prop values into
    `PerformanceMeasure.detail.devtools.properties` on every render. Those entries
    remain in the renderer's performance timeline until cleared and can make the
    process footprint grow by gigabytes while the JS heap and DOM stay bounded.
    
    Suspect this path when a CPU profile contains `logComponentRender`,
    `addValueToProperties`, or `performance.measure`. Inspect entry counts and
    string lengths without returning or serializing the retained values:
    
    ```js
    var timingSummary = await page.evaluate(() => {
      var measures = performance.getEntriesByType("measure")
      var reactMeasures = 0
      var largestProperty = null
    
      for (var entry of measures) {
        var devtools = entry.detail?.devtools
        if (devtools?.track !== "Components ⚛") continue
        reactMeasures++
    
        for (var property of devtools.properties ?? []) {
          if (!Array.isArray(property)) continue
          for (var value of property) {
            if (
              typeof value === "string" &&
              value.length > (largestProperty?.length ?? 0)
            ) {
              largestProperty = { component: entry.name, length: value.length }
            }
          }
        }
      }
    
      return { totalMeasures: measures.length, reactMeasures, largestProperty }
    })
    ```
    
    Do not call `JSON.stringify()` on all performance entries or return their
    `detail` objects over CDP; that creates another large copy and contaminates the
    measurement.
    
    To distinguish retained diagnostic entries from an application leak:
    
    1. Stop or finish the bounded scenario and capture OS, heap, DOM, and timing
       counts.
    2. Save any required trace before cleanup; clearing removes evidence from the
       current User Timing buffer.
    3. Run `performance.clearMeasures()` and `performance.clearMarks()` in the
       page.
    4. Only for this explicit post-cleanup comparison, run
       `HeapProfiler.collectGarbage` and resample the same gauges.
    5. If measures immediately accumulate again, rendering is still active; wait
       for the same idle state and repeat once.
    
    A sharp process-footprint drop after cleanup, with bounded heap and DOM, is
    evidence of development instrumentation retention rather than an equivalent
    production leak. It is not a product fix: never add content truncation,
    memoization, or stream throttling solely to hide this signal. If production
    impact matters, verify it independently against the current production bundle
    or packaged build and report separately whether that validation was run.
    
    ## Node and main-process checks
    
    Identify the busy process before profiling. Sample the tracked process group
    several times before, during, and after:
    
    ```bash
    ps -axo pid=,ppid=,pgid=,%cpu=,rss=,command= | \
      awk '$3 == <TRACKED_PGID>'
    ```
    
    Separate Electron main, renderer/helper, GPU, Vite, runner, and spawned child
    process costs. A Claude Code or MCP child is not part of the Electron main V8
    isolate even when it shares the process group; profile the PID that actually
    owns the CPU or memory.
    
    ### Prefer the built-in main-process diagnostics
    
    For startup, lifecycle, database, DataApi, or IPC latency, first read
    [Performance Diagnostics](../../../../docs/dev/references/diagnostics/README.md). Restart the
    tracked instance with `CS_DIAGNOSTICS=1` prepended to its existing launch
    command only when the restart is justified by the question. The opt-in path
    provides:
    
    - a `boot-whenReady.cpuprofile` with 1000 microsecond V8 samples;
    - lifecycle service spans and event-loop lag;
    - slow better-sqlite3 queries, DataApi requests, and IPC handlers;
    - window construction and ready-to-show timings.
    
    Keep the sampling interval at 1000 microseconds. Sort CPU profiles by self time;
    wall time assigned to async service initialization can include sibling work and
    is not reliable attribution.
    
    Interpret the combined signals:
    
    | Observation | Likely class | Next evidence |
    | --- | --- | --- |
    | High CPU and profiler self time | Synchronous JavaScript or native call site | Inspect the hottest stack and bound the same input |
    | High event-loop lag | Main thread blocked | Correlate the lag window with CPU, DB, IPC, and logs |
    | Long wall time, low CPU, low lag | Async I/O, network, timer, or subprocess wait | Trace start/end timestamps and the external dependency |
    | `fires=0` during a long startup phase | Microtask chain never yielded | Trust CPU self time, not timer-based lag |
    | Slow better-sqlite3 query plus lag | Synchronous database work | Inspect SQL, row count, query plan, and transaction scope |
    
    ### Profile steady-state Node work
    
    For runtime work outside startup, verify that the recorded Node inspector port,
    normally `9229`, belongs to the exact Electron main PID. Inspect
    `http://127.0.0.1:<INSPECTOR_PORT>/json/list`, attach to that target, and collect
    only a bounded reproduction with `Profiler.enable`,
    `Profiler.setSamplingInterval({ interval: 1000 })`, `Profiler.start`, and
    `Profiler.stop`. Save the returned profile under
    `.context/cherry-electron-dev/` and detach the inspector connection afterward.
    Do not confuse the main-process inspector with renderer CDP, normally `9222`.
    
    Do not leave the CPU profiler running while waiting for user input or an
    unbounded stream. Sampling has overhead, and an oversized profile is harder to
    attribute. Compare the same duration and input, and use source-mapped stacks
    from the tracked debug instance.
    
    If the exact main PID has high CPU but the V8 profile does not account for it,
    capture a short native sample of that PID on macOS:
    
    ```bash
    sample <ELECTRON_MAIN_PID> 10 -file \
      .context/cherry-electron-dev/main-native-sample.txt
    ```
    
    This gap points toward Electron, a native addon, another main-process thread,
    or the wrong PID—not automatically toward JavaScript. Keep native samples under
    `.context`; stacks and paths may be private.
    
    ### Diagnose Node memory growth
    
    At matched idle checkpoints, record both OS RSS/footprint and main-isolate
    memory from `process.memoryUsage()` through inspector `Runtime.evaluate`. Return
    only numeric fields and aggregate resource types; do not return application
    objects or message contents over the inspector channel.
    
    ```js
    (() => {
      var memory = process.memoryUsage()
      var resources = process.getActiveResourcesInfo?.() ?? []
      var resourcesByType = {}
      for (var type of resources) {
        resourcesByType[type] = (resourcesByType[type] ?? 0) + 1
      }
      return { ...memory, resourcesByType }
    })()
    ```
    
    Use repeated, fixed-size cycles and return to the same idle state before each
    sample:
    
    - rising `heapUsed` after comparable post-GC checkpoints suggests retained JS
      objects;
    - rising `external` or `arrayBuffers` suggests Buffer, typed-array, or native
      backing-store retention;
    - rising handle/resource counts suggest timers, sockets, pipes, or requests
      that were not released;
    - rising OS footprint with bounded isolate fields points toward Electron/native
      allocations, SQLite/native addons, allocator fragmentation, or another
      process—not proof of a JavaScript leak.
    
    Capture the raw checkpoint first. When a post-GC discriminator is necessary,
    call `HeapProfiler.collectGarbage` through the same main-process inspector and
    resample after a fixed quiet delay. Compare post-GC checkpoints with each
    other; do not compare a forced-GC result with an arbitrary pre-GC peak. A heap
    drop without an RSS drop can be allocator retention rather than live objects.
    
    Use `HeapProfiler.startSampling` for bounded allocation attribution. Reserve a
    full heap snapshot for cases sampling cannot resolve: it pauses the main
    process, can be very large, and may contain tokens, prompts, paths, or other
    private data. Never expose the main inspector beyond loopback, and do not add
    permanent diagnostic logging or instrumentation until existing evidence shows
    which boundary lacks observability.
    
    ## Startup analysis
    
    Startup profiling requires a restart:
    
    1. Explain and record the current instance/scenario.
    2. Gracefully stop only the tracked instance.
    3. Start the same debug command and profile.
    4. Preserve startup logs and timestamps.
    5. Measure navigation milestones such as `NavigationStart`,
       `DomContentLoaded`, and `FirstMeaningfulPaint`.
    6. Update `instance.json` and keep the replacement running.
    
    Separate native rebuild, main bootstrap, database migration, service startup,
    renderer load, and first interactive UI. Do not treat the whole `pnpm debug`
    duration as app startup.
    
    ## Interpretation and reporting
    
    - Script-heavy `TaskDuration` suggests JavaScript/React work.
    - Layout/style deltas suggest DOM measurement or CSS invalidation.
    - Repeated long trace tasks identify likely jank sources.
    - Heap plus node/listener growth after identical idle cycles suggests a leak.
    - Quiet renderer plus high main CPU points to services or IPC.
    - High helper/GPU CPU without renderer task growth points to media, canvas,
      GPU, or embedded web content.
    
    Report exact PID/target/route/scenario/duration, baseline and scenario deltas,
    artifact paths, strongest evidence, uncertainty, and before/after comparison
    for a fix. Keep Electron running after collection unless restart was explicitly
    part of the profile.
    
  • .agents/skills/cherry-electron-dev/references/pr-testing.md5.3 KB8607400529e4upstream ↗
    # PR Testing
    
    Use this workflow for a bounded PR test within `cherry-electron-dev`. For
    ongoing implementation or debugging, follow the skill's development loop.
    
    ## Prerequisites and safety
    
    - Require authenticated `gh`, `pnpm`, and installed project dependencies.
    - Use Playwright/CDP or optional `agent-browser` for UI control.
    - Before touching Electron, read
      [Electron Instance Management](electron-instance.md)
      and select its `ephemeral` policy.
    - Treat that reference as the only authority for discovery, target selection,
      launch, replacement, shutdown, tracking, and troubleshooting.
    - Never discard local changes. Stop and ask if checkout would overwrite them.
    - Show the report before posting it anywhere.
    
    `$ARGUMENTS` may contain a PR number, PR URL, `latest`/`recent`, or nothing.
    
    ## Workflow
    
    ### 1. Resolve and inspect the PR
    
    If no PR is specified, list recent PRs and ask the user to choose unless they
    requested the latest:
    
    ```bash
    gh pr list --repo CherryHQ/cherry-studio --state open --limit 10 \
      --json number,title,author,createdAt,headRefName,changedFiles
    ```
    
    Record the current branch for restoration, inspect the PR, then check it out:
    
    ```bash
    git status --short
    git branch --show-current
    gh pr view <NUMBER> --json title,body,author,headRefName,headRefOid,files
    gh pr checkout <NUMBER>
    ```
    
    Read the changed files and nearby instructions. Record the exact checked-out
    HEAD and verify it matches the resolved PR head.
    
    ### 2. Analyze and start the app
    
    Run static analysis while the app starts when both can proceed independently.
    
    Inspect existing CI results with `gh pr checks <NUMBER>`. Follow current
    repository instructions for local validation: use explicit affected test file
    paths when needed, and do not default to full lint, test, or typecheck suites.
    Record which checks ran locally, which ran in CI, and any coverage gaps.
    
    Read the changed code and check:
    
    - blocked or deprecated v1/v2-refactor files
    - hardcoded user-visible strings instead of i18n
    - `console.log` instead of `loggerService`
    - missing types on new public interfaces
    
    For Electron:
    
    1. Use the shared reference to verify existing instances.
    2. Reuse only an instance from this workspace whose recorded launch HEAD equals
       the checked-out PR HEAD.
    3. When reusing one, mark it borrowed and preserve its existing policy and
       ownership. Never reclassify a persistent instance as ephemeral.
    4. Otherwise gracefully replace only the verified same-workspace instance.
    5. Launch an `ephemeral`, agent-owned instance with an isolated
       `CS_DEV_USER_DATA_SUFFIX`, such as `PR-<NUMBER>`.
    6. Keep its managed terminal/session, PIDs, ports, log, exact target, and
       `pr-test:<NUMBER>` launch purpose in
       `instance.json`.
    
    Do not use broad process or port cleanup.
    
    ### 3. Run interactive tests
    
    Bind the controller to the exact target returned by the shared reference.
    Never navigate to a guessed root URL or select a target by index.
    
    Build test cases from the PR description and changed files:
    
    1. Capture the initial state.
    2. Inspect interactive elements with the available CDP controller.
    3. Exercise the changed behavior.
    4. Capture the result and verify relevant persisted state.
    5. Repeat edge cases justified by the change.
    
    Consider UI rendering, interactions, persistence, light/dark themes, relevant
    window sizes, i18n, empty states, and rapid interaction only when in scope.
    
    Store screenshots and the report under `.context/cherry-electron-dev/pr-<NUMBER>/`:
    
    ```bash
    mkdir -p .context/cherry-electron-dev/pr-<NUMBER>
    ```
    
    If an isolated profile shows the migration wizard or splash, follow the shared
    troubleshooting guidance and startup logs. Do not reset or force-close data.
    
    ### 4. Clean up and restore
    
    Perform cleanup and restoration even if testing fails or is blocked, and
    report any incomplete cleanup or restoration.
    
    Use the shared `ephemeral` finish procedure. Stop only an instance launched by
    this PR-test workflow whose verified record remains `ephemeral`, agent-owned,
    and scoped to `pr-test:<NUMBER>`. Leave every borrowed instance running. Do not
    stop unrelated workspaces or packaged apps.
    
    Restore the branch recorded before checkout. If it no longer exists, resolve
    the repository default branch and report the fallback before switching:
    
    ```bash
    git checkout <ORIGINAL_BRANCH>
    ```
    
    ### 5. Report
    
    Save `.context/cherry-electron-dev/pr-<NUMBER>/report.md` and show it to the user.
    Match the report language to the user's language; the template uses English labels:
    
    ```markdown
    # PR #<NUMBER> Test Report
    
    **Title**: <title>
    **Author**: @<author>
    **Branch**: <branch>
    **Tested HEAD**: <commit SHA>
    **Changed files**: <count>
    
    ## Static Analysis
    
    | Check | Result | Notes |
    | --- | --- | --- |
    | CI checks | ✅/❌/pending | ... |
    | Local checks | ✅/❌/not run | <exact commands and scope> |
    | Blocked-file check | ✅/⚠️ | ... |
    | Logging, i18n, and types | ✅/❌ | ... |
    
    ## UI Tests
    
    ### <Test Case>
    
    <scenario, evidence, and result>
    
    ![screenshot](<filename>.png)
    
    ## Findings
    
    <findings or none>
    
    ## Runtime and Cleanup
    
    <verified PID, CDP port, tracking file, evidence paths, whether the instance
    was started or borrowed, final process state, and restored branch>
    
    ## Conclusion
    
    - Total findings: N
    - Recommendation: APPROVE / REQUEST_CHANGES / COMMENT
    ```
    
    Do not post the report or submit a GitHub review unless the user explicitly
    asks.
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/cherryhq-cherry-studio-agents-skills-cherry-electron-dev.md

// REPO STATS

53.5k stars
1772 open issues
Last commit: 8h ago