generated from BlackHatMagic/Template-Bare
feat: add Pi chat sidebar plugin #1
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/chat-panel"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
PR Type Selection
Summary
Adds Pi Chat, a desktop Obsidian plugin that runs the installed Pi coding agent in the right sidebar. It spawns the normal
piCLI in--mode rpcwith the vault root as the working directory, streams assistant/reasoning/tool activity, and uses the vault's active theme through Obsidian CSS variables.The interface follows the T3 Chat / Pi web workspace layout, adapted to Obsidian's narrower sidebar: native view actions, model and reasoning selectors, a compact status row, collapsible tool and reasoning blocks, and a composer with steering/follow-up modes.
Related Issues
None. This is the initial plugin implementation.
Design Overview
ChatStateholds display messages, tool states, queue, model catalog, and session metadata.applyRecordincrementally reconstructs streaming message blocks frommessage_updatedeltas and applies completion events authoritatively. Full transcript renders are signature-gated so token deltas update only the live text nodes.ItemView(pi-chat-view), ribbon icon, four commands (open, new chat, restart, compact), and a settings tab.PiClientis a typed RPC command/response client with process lifecycle handling.PiSessionowns Pi startup, hydration, model/thinking persistence, prompts, abort, and compaction.Implementation Notes
--session-dir <plugin>/sessions --session-id <id>; they persist across reloads but stay out of the vault and Obsidian Sync.PI_OBSIDIAN_PI, augmentedPATH(including mise shims), known install locations, thenmise exec -- pi. GUI-launched Obsidian often does not inherit the shell's PATH, so this fallback matters.select,confirm,input,editor) map to an Obsidian modal; extension notifications map toNotice; fire-and-forget widgets are intentionally not rendered.--background-primary,--text-muted,--interactive-accent, etc.). No plugin palette or theme toggle.message_end, then Markdown is rendered by Obsidian so links, tables, and code highlighting behave natively.Testing Evidence
tests/chat-state.test.ts(stream reconstruction, tool-result attachment, history, queues, skill blocks, hidden custom/system messages);tests/launcher.test.ts(PATH lookup, explicit path, child environment).bun run checkpasses:tsc --noEmitplus 9 tests.bun run buildproducesmain.js.pi --mode rpcchild throughPiClientandPiSession; hydrated 29 models and thinking levels; ran a prompt end-to-end (OK), ran a realreadtool call against a temp note and confirmed tool/result blocks, then stopped and restarted the session and confirmed transcript restoration.Documentation
Checklist (Feature-Specific)
Additional Notes
isDesktopOnly: true).Pi code review
8 new actionable findings
src/chat-view.ts:357src/pi-client.ts:53src/chat-view.ts:259src/chat-view.ts:516src/chat-view.ts:604src/launcher.ts:119styles.css:110README.md:127Reviewed initial Pi Chat plugin covering RPC client, session lifecycle, reducer, sidebar rendering, launcher and styling. This is a static aggregation of three independent read-only reviews without builds, tests, or live Pi execution.
Change walkthrough
.gitignore,manifest.json,src/chat-state.ts,src/chat-view.ts(+10 more)README.mdbun.lock,esbuild.config.mjs,package.json,tsconfig.jsontests/chat-state.test.ts,tests/launcher.test.tsReview effort: 3/5.
Static observations (not validation results)
Reviewed
5ec02574dc4ab89823e83e4c2ae6644e1368ed78withproxy/glm-5.3-flash + proxy/gpt-6.1-sol + proxy/muse-spark-1.3 → proxy/muse-spark-1.3. Automated advisory review; no project commands or tests were executed.@ -35,0 +124,4 @@## LicenseMIT. See [LICENSE.md](LICENSE.md).[P2] README and package claim MIT but LICENSE is AGPL-3.0
README states MIT and package.json declares MIT while referenced LICENSE.md is AGPL-3.0, giving contradictory terms for same code.
Trigger: Anyone reading README, package metadata, or LICENSE.md.
Impact: License confusion with legal consequences for redistribution under wrong terms.
Evidence: LICENSE.md at head is GNU AFFERO GENERAL PUBLIC LICENSE Version 3; README License section says MIT; package.json sets license MIT.
@ -0,0 +256,4 @@try {await this.plugin.getSession().prompt(text, this.behavior);} catch (error) {this.composer.value = text;[P2] Failed send overwrites newer composer draft
send() clears the composer then awaits prompt without locking editing; on failure it unconditionally restores the old text and draft, discarding anything typed while waiting.
Trigger: Send a message, start typing the next message, then the outstanding start/prompt request fails from Pi exit or timeout.
Impact: Newer unsent user text and its localStorage draft are lost with no recovery.
Evidence: src/chat-view.ts send clears composer before await PiSession.prompt and assigns captured text back in catch without checking current value; input stays editable and persists newer text, while PiSession.prompt/PiClient reject on process failure or timeout.
@ -0,0 +354,4 @@if (force || signature !== this.renderedMessageSignature || toolSignature !== this.renderedToolSignature) {this.renderMessages(state);this.renderedMessageSignature = signature;this.renderedToolSignature = toolSignature;[P2] Queued steering/follow-up chips not rendered while streaming
The fast live-update path returns after updating only text and tool nodes, skipping renderQueue. Queue changes do not affect message or tool signatures, so chips stay stale for the whole streaming run until a full re-render.
Trigger: While a live assistant message is streaming, a queue_update arrives, e.g. user sends Next step/After task while Pi works or Pi consumes a queued item.
Impact: Users get no or stale confirmation that steering/follow-up was queued or consumed, defeating the queue UI purpose.
Evidence: src/chat-view.ts render():
if (canUpdateLive && live) { this.updateLiveMessage(live); this.updateToolNodes(state); return; }skips renderQueue; queue_update only writes state.queue and messageSignature/toolSignature cover only messages/tools.Suggested fix:
@ -0,0 +513,4 @@private renderBlock(parent: HTMLElement, block: ChatBlock, message: ChatMessage, index: number): void {if (block.type === "text") {if (!block.text.trim()) return;[P2] Initially empty streaming text block never appears
renderBlock omits empty text blocks, but later deltas use the incremental path that cannot create the missing node, so the answer stays invisible until a structural re-render.
Trigger: Pi emits text_start and first nonempty text_delta arrives after next animation frame, with no new block added during the answer.
Impact: Primary streaming response is hidden until message_end instead of streaming visibly.
Evidence: src/chat-state.ts applyAssistantDelta creates empty text block for text_start; src/chat-view.ts renderBlock returns early if !block.text.trim(); messageSignature excludes streaming text lengths so canUpdateLive holds and updateLiveMessage queries absent data-block-index and skips.
@ -0,0 +601,4 @@if (!(el instanceof HTMLElement)) continue;if (el.classList.contains("pi-chat-streaming-text") && block.type === "text" && el.textContent !== block.text) {el.setText(block.text);} else if (el.classList.contains("pi-chat-thinking-text") && block.type === "thinking" && el.textContent !== block.text) {[P2] Reasoning text does not update while streaming
Incremental updater selects the details element carrying data-block-index but tests it for the child-only thinking-text class, so the condition never succeeds and expanded reasoning stays frozen.
Trigger: Use reasoning model with thinking block expanded or Expand thinking enabled while thinking deltas arrive for same block.
Impact: Users cannot monitor ongoing reasoning; content stays empty or stale until full render.
Evidence: src/chat-view.ts places data-block-index on details and pi-chat-thinking-text on nested div; updateLiveMessage selects data-block-index element and tests same element for pi-chat-thinking-text; streaming thinking does not change messageSignature.
@ -0,0 +116,4 @@for (const path of knownPiPaths(homedir())) {if (existsSync(path)) candidates.push({ command: path, args: bases, source: "Known install location" });}for (const candidate of candidates) {[P2] Invalid configured Pi path silently falls back to another binary
resolvePiLaunch treats explicit setting as just one candidate and returns first executable, so a typo or non-executable configured path falls through to PATH/known locations/mise instead of erroring.
Trigger: Set Settings Pi executable to non-existent or non-executable path while working pi exists on augmented PATH or known location.
Impact: Runs a different Pi binary than user pinned, defeating explicit configuration and hiding the error; may run unexpected binary.
Evidence: src/launcher.ts loops candidates and returns first executable; configuredValue only changes final throw message, contradicting comment that explicit setting always wins.
Suggested fix:
@ -0,0 +50,4 @@async start(timeoutMs = 20_000): Promise<void> {if (this.child) return;const { cwd, launch, env } = this.options;const child = spawn(launch.command, launch.args, {[P2] Windows npm Pi shims cannot be spawned without shell
Launcher accepts Windows .CMD/.BAT and extensionless shims as winning candidates, but PiClient spawns the path directly with no shell, which Node/Electron rejects for .cmd/.bat and cannot execute POSIX sh shims.
Trigger: Open chat on Windows with Pi installed via npm with its shim directory on PATH, or configured as pi.cmd.
Impact: Pi child fails to start so chat is unavailable on a common Windows install layout.
Evidence: src/launcher.ts pathExtensions includes ""/.CMD/.BAT and executable() skips format checks on win32, so findOnPath can return pi.cmd or POSIX pi; src/pi-client.ts spawn uses {cwd, env, stdio, windowsHide:true} with no shell option, and PiSession.doStart uses that launch unchanged.
@ -0,0 +107,4 @@white-space: nowrap;}.pi-chat-status-dot {[P2] Status dot always shows error/pulse state
Busy and error dot rules are written as plain .pi-chat-status-dot so they unconditionally override idle style; qualifiers were applied to text element instead.
Trigger: Open Pi Chat in any state and observe status dot.
Impact: Idle chats show red pulsing dot, misrepresenting busy/error and removing dot distinction for real errors.
Evidence: styles.css defines idle faint dot, then unconditionally sets accent+animation and later error background on .pi-chat-status-dot; .is-busy/.is-error qualifiers only target .pi-chat-status-text.
Suggested fix:
Pi code review
2 new actionable findings
src/pi-client.ts:53src/session.ts:320Earlier findings: 8 rechecked
src/pi-client.ts:53, first reported in review #230) — src/launcher.ts pathExtensions() excludes extensionless candidates on win32, needsShell() marks .cmd/.bat, and src/pi-client.ts spawn passes shell: launch.shell.README.md:127, first reported in review #230) — package.json license is AGPL-3.0-only, README License section reads AGPL-3.0, matching LICENSE.md AGPL text.src/launcher.ts:119, first reported in review #230) — src/launcher.ts resolvePiLaunch() throws PiNotFoundError when a non-empty configured value cannot be resolved to an executable file and returns it directly instead of falling back.src/chat-view.ts:259, first reported in review #230) — src/chat-view.ts send() catch only restores the captured text when the current composer is empty after trimming, preserving newer drafts.styles.css:110, first reported in review #230) — styles.css scopes accent/pulse to .pi-chat-status.is-busy .pi-chat-status-dot and error color to .pi-chat-status.is-error .pi-chat-status-dot.src/chat-view.ts:357, first reported in review #230) — Not rechecked by this review; kept open for the next one.src/chat-view.ts:516, first reported in review #230) — Not rechecked by this review; kept open for the next one.src/chat-view.ts:604, first reported in review #230) — Not rechecked by this review; kept open for the next one.Merged three candidate reviews of the initial Pi Chat plugin at
b18c4a5; verified current code by inspection without running builds or Pi/Obsidian runtimes. All eight prior findings are fixed in head, with two residual concurrency and Windows launch defects carried forward.Change walkthrough
src/main.ts,src/pi-client.ts,src/session.ts,src/launcher.ts(+6 more)Review effort: 4/5.
Static observations (not validation results)
Reviewed
b18c4a538df4bcf0586fbbcdc4b8522bd8316ccfwithproxy/glm-5.3-flash + proxy/gpt-6.1-sol + proxy/muse-spark-1.3 → proxy/muse-spark-1.3. Automated advisory review; no project commands or tests were executed.@ -0,0 +50,4 @@async start(timeoutMs = 20_000): Promise<void> {if (this.child) return;const { cwd, launch, env } = this.options;const child = spawn(launch.command, launch.args, {[P2] Windows shell launches do not preserve paths containing spaces
Enabling shell execution for .cmd/.bat shims passes the executable and session directory to cmd.exe without shell quoting. Node shell-mode spawn joins command and arguments into a command string rather than preserving argv boundaries, so spaces in the install or vault path break the launch or truncate the session-directory argument.
Trigger: Open chat on Windows using an npm pi.cmd shim with a space in its executable path or the vault/plugin path, such as a vault named My Notes.
Impact: Chat can fail to start on a common Windows layout, or Pi can receive a truncated session directory and store sessions outside the intended plugin folder.
Evidence: src/launcher.ts needsShell() enables shell execution for .cmd/.bat; src/session.ts appends the raw host.sessionDir as an argument derived from the vault/plugin folder in src/main.ts; src/pi-client.ts passes those raw values directly to spawn with shell: launch.shell with no quoting or shim-to-native conversion. The Windows launcher test only checks resolution and the shell flag, not execution with these paths.
@ -0,0 +317,4 @@}async newSession(): Promise<void> {await this.stop();[P2] Overlapping New chat operations can lose the persisted session reference
newSession() does not serialize the stop/save/start sequence. A second invocation can start a new child while the first is still stopping the old child; the first invocation then overwrites the saved session ID, but start() reuses the second invocation's already-running or starting child.
Trigger: Invoke New chat twice while an existing child is stopping, for example by double-clicking the settings tab New chat button. PiClient.stop() can remain pending for several seconds.
Impact: The running chat and settings can refer to different session IDs. Messages written by the running child are not restored after reload because startup opens the other saved ID, leaving the conversation apparently lost.
Evidence: src/settings.ts exposes an async New chat button without disabling or serializing it, and src/main.ts startNewSession() forwards directly to session.newSession(). In src/session.ts stop() sets this.client to null before awaiting client.stop(), allowing a second stop() to finish immediately. Each newSession() independently saves a fresh ID while start()/doStart() reuse this.starting or an already-running child rather than checking which session ID that child owns.
Pi code review
3 new actionable findings
src/chat-view.ts:357src/chat-view.ts:221src/pi-client.ts:224Earlier findings: 5 rechecked
src/chat-view.ts:357, first reported in review #230) — src/chat-view.ts render() canUpdateLive branch now calls this.renderQueue(state) before returning, so queue chips update during streaming.src/pi-client.ts:53, first reported in review #232) — src/pi-client.ts builds quoted cmd /d /s /c line via quoteWindowsArgument/windowsShellInvocation with windowsVerbatimArguments:true; tests/pi-client.test.ts asserts quoting for paths with spaces.src/session.ts:320, first reported in review #232) — src/session.ts routes start/stop/restart/newSession through enqueue()/lifecycle promise chain, so overlapping New chat sequences run in submission order.src/chat-view.ts:516, first reported in review #230) — src/chat-view.ts renderBlock() only skips empty text when !message.streaming and renders .pi-chat-streaming-text node with data-block-index for live updates.src/chat-view.ts:604, first reported in review #230) — src/chat-view.ts thinking text div now carries data-block-index and updateLiveMessage queries .pi-chat-thinking-text[data-block-index], matching the live node.Reviewed the initial Pi Chat plugin at head against its feature intent, covering RPC lifecycle, reducer, sidebar UI, launcher and docs. Verification was read-only from current code and candidate evidence with no builds, tests, or live Pi/Obsidian runs.
Change walkthrough
src/chat-view.ts,src/chat-state.ts,src/session.ts,src/pi-client.ts(+5 more)tests/chat-state.test.tsReview effort: 4/5.
Static observations (not validation results)
Reviewed
eed88bff6e6770a961c73dcee45cc20ffc358ffbwithproxy/glm-5.3-flash + proxy/gpt-6.1-sol + proxy/muse-spark-1.3 → proxy/muse-spark-1.3. Automated advisory review; no project commands or tests were executed.@ -0,0 +218,4 @@});const suggestions = this.emptyEl.createDiv({ cls: "pi-chat-suggestions" });for (const [icon, label, prompt] of [["file-search", "Summarize the active note", "Summarize the note I'm currently viewing. Mention its main ideas and open questions."],[P2] Active-note suggestions omit the note's identity
The Summarize the active note and Find related notes suggestions populate only generic referring text and never supply the active file path, so Pi cannot identify the intended note.
Trigger: Open a note in a multi-note vault, click either active-note suggestion in an empty chat, and send it without separately using the file-path insertion button.
Impact: Advertised shortcuts cannot reliably perform their task; Pi must ask for the missing note or infer a potentially wrong target.
Evidence: src/chat-view.ts buildEmptyState defines prompts containing only currently viewing/active note and the click handler assigns that literal to the composer; send() forwards trimmed text via PiSession.prompt() with only streamingBehavior, while cwd is the vault root and insertActiveNote() is a separate explicit action never invoked by the suggestions.
@ -0,0 +354,4 @@signature === this.renderedMessageSignature &&toolSignature === this.renderedToolSignature;if (canUpdateLive && live) {this.updateLiveMessage(live);[P2] Long streamed answers stop following the transcript bottom
The incremental live-update path grows the live message without preserving bottom-following, so once a single text block streams past the viewport the new output falls below the visible scroll position.
Trigger: Transcript is scrollable with user at bottom and an assistant text block streams enough content to extend more than 100px below the viewport without adding another block, staying in the canUpdateLive path.
Impact: Users must repeatedly scroll manually to monitor normal long answers and can remain above the completed answer after streaming ends.
Evidence: src/chat-view.ts render() canUpdateLive branch updates live text via updateLiveMessage() which only changes textContent and returns without checking scroll; isNearBottom()/scrollToBottom() are only used in renderMessages(), whose near-bottom check runs after scrollHeight already grew so it restores stale previousScroll.
Suggested fix:
@ -0,0 +221,4 @@}const exit = new Promise<void>((resolve) => child.once("exit", () => resolve()));child.stdin.end();const terminate = setTimeout(() => child.kill("SIGTERM"), 2_000);[P2] Windows shim launches can orphan the pi process on stop/restart
When Pi is launched through a .cmd/.bat shim the direct child is cmd.exe and stop() kills only that child, so a pi grandchild that does not exit promptly on stdin EOF can survive with no controlling client.
Trigger: Windows with npm pi.cmd shim via PATH/PATHEXT with stop/restart/new-chat while pi does not exit within the 2s grace after stdin EOF, e.g. during an in-flight run.
Impact: Surviving pi keeps holding the session file with no UI supervision and a subsequent restart reuses the same --session-id, risking interleaved transcript writes and unsupervised vault/tool activity.
Evidence: src/pi-client.ts stop() does child.stdin.end() then child.kill("SIGTERM"/"SIGKILL") against the direct child which is cmd.exe via windowsShellInvocation; src/launcher.ts needsShell() routes .cmd/.bat to this path and src/session.ts restart()/doStop()/doStart() reuse the same saved sessionId for the replacement child.
Pi code review
0 new actionable findings
No new actionable findings. Previously reported issues, if any, are tracked below.
Earlier findings: 3 rechecked
src/chat-view.ts:357, first reported in review #234) — src/chat-view.ts render() canUpdateLive branch now captures const stick = this.isNearBottom() before updateLiveMessage()/updateToolNodes() and calls if (stick) this.scrollToBottom(), preserving bottom-follow during streaming growth.src/chat-view.ts:221, first reported in review #234) — src/chat-view.ts buildEmptyState() marks two suggestions needsNote=true, resolves getActiveFile() on click, and appends Active note: ${note.path} to composer text when a note is active.src/pi-client.ts:224, first reported in review #234) — src/pi-client.ts terminate() spawns taskkill /pid <pid> /t /f for launch.shell on win32 with child.kill fallback, and stop()/fail() route through terminate(), killing the cmd shim tree rather than only cmd.exe.Merged three independent reviews of the initial Pi Chat plugin at head
85f5816; all prior threads verified fixed in current code via static inspection only, with no live Obsidian, build, or test execution.Change walkthrough
src/chat-view.ts,src/chat-state.ts,src/pi-client.ts,src/session.ts(+8 more)tests/chat-state.test.ts,tests/launcher.test.ts,tests/pi-client.test.tsREADME.mdpackage.json,esbuild.config.mjs,tsconfig.jsonReview effort: 3/5.
Static observations (not validation results)
Reviewed
85f5816a9d2be7f682aa38054c3686c6228823b7withproxy/glm-5.3-flash + proxy/gpt-6.1-sol + proxy/muse-spark-1.3 → proxy/muse-spark-1.3. Automated advisory review; no project commands or tests were executed.