Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add terminal-preview linking functionality #1852

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions frontend/app/view/preview/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import { createRef, memo, useCallback, useEffect, useMemo, useState } from "reac
import { CSVView } from "./csvview";
import { DirectoryPreview } from "./directorypreview";
import "./preview.scss";
import { useTerminalPreviewSync } from "./sync";
import { toggleTerminalPreviewLink } from "./sync";

const MaxFileSize = 1024 * 1024 * 10; // 10MB
const MaxCSVSize = 1024 * 1024 * 1; // 1MB
Expand Down Expand Up @@ -172,6 +174,7 @@ export class PreviewModel implements ViewModel {
refreshCallback: () => void;
directoryKeyDownHandler: (waveEvent: WaveKeyboardEvent) => boolean;
codeEditKeyDownHandler: (waveEvent: WaveKeyboardEvent) => boolean;
isUpdatingFromTerminal: boolean;

constructor(blockId: string, nodeModel: BlockNodeModel) {
this.viewType = "preview";
Expand Down Expand Up @@ -450,6 +453,7 @@ export class PreviewModel implements ViewModel {
});

this.noPadding = atom(true);
this.isUpdatingFromTerminal = false;
}

markdownShowTocToggle() {
Expand Down Expand Up @@ -528,6 +532,31 @@ export class PreviewModel implements ViewModel {
const blockOref = WOS.makeORef("block", this.blockId);
await services.ObjectService.UpdateObjectMeta(blockOref, updateMeta);

const linkedTerminalId = blockMeta?.["preview:linked_terminal"];
if (linkedTerminalId && !this.isUpdatingFromTerminal) {
try {
const fileInfo = await RpcApi.FileInfoCommand(TabRpcClient, {
info: {
path: await this.formatRemoteUri(newPath, globalStore.get),
},
});
if (fileInfo?.isdir) {
const terminalBlockRef = WOS.makeORef("block", linkedTerminalId);
await services.ObjectService.UpdateObjectMeta(terminalBlockRef, {
"cmd:cwd": fileInfo.dir
});

await RpcApi.ControllerInputCommand(TabRpcClient, {
blockid: linkedTerminalId,
inputdata64: btoa(`cd "${fileInfo.dir}"\n`),
});
}
} catch (error) {
console.error("Failed to sync terminal directory:", error);
// Consider showing a user-friendly error notification
}
}

// Clear the saved file buffers
globalStore.set(this.fileContentSaved, null);
globalStore.set(this.newFileContent, null);
Expand Down Expand Up @@ -685,6 +714,29 @@ export class PreviewModel implements ViewModel {
await navigator.clipboard.writeText(fileInfo.name);
}),
});

menuItems.push({ type: "separator" });
menuItems.push({
label: "Link to Terminal (from clipboard)",
click: () =>
fireAndForget(async () => {
const terminalId = await navigator.clipboard.readText();
if (!terminalId) return;
await toggleTerminalPreviewLink(terminalId, this.blockId);
}),
});

menuItems.push({
label: "Unlink from Terminal",
click: () =>
fireAndForget(async () => {
const linkedTerminalId = globalStore.get(this.blockAtom)?.meta?.["preview:linked_terminal"];
if (linkedTerminalId) {
await toggleTerminalPreviewLink(linkedTerminalId, this.blockId);
}
}),
});

Comment on lines +717 to +739
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing the terminal linking UX.

The current implementation has several areas for improvement:

  1. Using clipboard for terminal ID transfer is error-prone
  2. No validation of terminal ID format or existence
  3. Missing user feedback on success/failure of linking/unlinking operations

Consider implementing:

  1. A terminal selector modal instead of clipboard
  2. Validation of terminal ID before linking
  3. User feedback through toast notifications
 menuItems.push({
-    label: "Link to Terminal (from clipboard)",
+    label: "Link to Terminal",
     click: () =>
         fireAndForget(async () => {
-            const terminalId = await navigator.clipboard.readText();
-            if (!terminalId) return;
+            // Show terminal selector modal
+            const terminalId = await showTerminalSelectorModal();
+            if (!terminalId) return;
+            
+            try {
                 await toggleTerminalPreviewLink(terminalId, this.blockId);
+                showToast("Terminal linked successfully");
+            } catch (error) {
+                showToast("Failed to link terminal: " + error.message, "error");
+            }
         }),
 });

Committable suggestion skipped: line range outside the PR's diff.

const mimeType = jotaiLoadableValue(globalStore.get(this.fileMimeTypeLoadable), "");
if (mimeType == "directory") {
menuItems.push({
Expand Down Expand Up @@ -1024,6 +1076,8 @@ function PreviewView({
model: PreviewModel;
}) {
const connStatus = useAtomValue(model.connStatus);
useTerminalPreviewSync(model);

if (connStatus?.status != "connected") {
return null;
}
Expand Down
86 changes: 86 additions & 0 deletions frontend/app/view/preview/sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0

import { atoms, globalStore } from "@/store/global";
import * as WOS from "@/store/wos";
import { PreviewModel } from "./preview";
import * as React from "react";
import { useAtomValue } from "jotai";
import { ObjectService } from "@/store/services";

declare module "@/store/wos" {
interface MetaType {
"preview:linked_terminal"?: string | null;
"cmd:cwd"?: string;
}
}

/**
* Synchronizes the Terminal's current working directory with the Preview's directory.
* This is used when the Terminal and Preview panes are linked.
*/
export function useTerminalPreviewSync(previewModel: PreviewModel) {
const blockData = useAtomValue(previewModel.blockAtom);
const linkedTerminalId = blockData?.meta?.["preview:linked_terminal"];

React.useEffect(() => {
if (!linkedTerminalId) {
return;
}

const terminalBlockAtom = WOS.getWaveObjectAtom(WOS.makeORef("block", linkedTerminalId));
const unsubscribe = globalStore.sub(terminalBlockAtom, () => {
const terminalBlock = globalStore.get(terminalBlockAtom);
const terminalCwd = terminalBlock?.meta?.["cmd:cwd"];
if (terminalCwd) {
previewModel.isUpdatingFromTerminal = true;
previewModel.goHistory(terminalCwd)
.catch(console.error)
.finally(() => {
previewModel.isUpdatingFromTerminal = false;
});
}
});

return () => {
unsubscribe();
previewModel.isUpdatingFromTerminal = false;
};
}, [linkedTerminalId, previewModel]);
}

/**
* Links or unlinks a Terminal and Preview pane for directory synchronization
*/
export async function toggleTerminalPreviewLink(terminalId: string, previewId: string) {
const previewBlockRef = WOS.makeORef("block", previewId);
const previewBlock = globalStore.get(WOS.getWaveObjectAtom(previewBlockRef));

if (previewBlock?.meta?.["preview:linked_terminal"] === terminalId) {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": null
});
return;
}

try {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": terminalId
});
} catch (err) {
console.error("Failed to update preview block metadata:", err);
// Optionally display an error notification to the user
}

const terminalBlock = globalStore.get(WOS.getWaveObjectAtom(WOS.makeORef("block", terminalId)));
const terminalCwd = terminalBlock?.meta?.["cmd:cwd"];
if (terminalCwd) {
const previewModel = new PreviewModel(previewId, null);
previewModel.isUpdatingFromTerminal = true;
try {
await previewModel.goHistory(terminalCwd);
} finally {
previewModel.isUpdatingFromTerminal = false;
}
}
}
Comment on lines +52 to +86
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for terminal and preview IDs.

The function should validate the input parameters to ensure they are non-empty strings and follow the expected format.

Apply this diff to add input validation:

 export async function toggleTerminalPreviewLink(terminalId: string, previewId: string) {
+    if (!terminalId?.trim() || !previewId?.trim()) {
+        throw new Error("Terminal ID and Preview ID must be non-empty strings");
+    }
+
     const previewBlockRef = WOS.makeORef("block", previewId);
     const previewBlock = globalStore.get(WOS.getWaveObjectAtom(previewBlockRef));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Links or unlinks a Terminal and Preview pane for directory synchronization
*/
export async function toggleTerminalPreviewLink(terminalId: string, previewId: string) {
const previewBlockRef = WOS.makeORef("block", previewId);
const previewBlock = globalStore.get(WOS.getWaveObjectAtom(previewBlockRef));
if (previewBlock?.meta?.["preview:linked_terminal"] === terminalId) {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": null
});
return;
}
try {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": terminalId
});
} catch (err) {
console.error("Failed to update preview block metadata:", err);
// Optionally display an error notification to the user
}
const terminalBlock = globalStore.get(WOS.getWaveObjectAtom(WOS.makeORef("block", terminalId)));
const terminalCwd = terminalBlock?.meta?.["cmd:cwd"];
if (terminalCwd) {
const previewModel = new PreviewModel(previewId, null);
previewModel.isUpdatingFromTerminal = true;
try {
await previewModel.goHistory(terminalCwd);
} finally {
previewModel.isUpdatingFromTerminal = false;
}
}
}
/**
* Links or unlinks a Terminal and Preview pane for directory synchronization
*/
export async function toggleTerminalPreviewLink(terminalId: string, previewId: string) {
if (!terminalId?.trim() || !previewId?.trim()) {
throw new Error("Terminal ID and Preview ID must be non-empty strings");
}
const previewBlockRef = WOS.makeORef("block", previewId);
const previewBlock = globalStore.get(WOS.getWaveObjectAtom(previewBlockRef));
if (previewBlock?.meta?.["preview:linked_terminal"] === terminalId) {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": null
});
return;
}
try {
await ObjectService.UpdateObjectMeta(previewBlockRef, {
"preview:linked_terminal": terminalId
});
} catch (err) {
console.error("Failed to update preview block metadata:", err);
// Optionally display an error notification to the user
}
const terminalBlock = globalStore.get(WOS.getWaveObjectAtom(WOS.makeORef("block", terminalId)));
const terminalCwd = terminalBlock?.meta?.["cmd:cwd"];
if (terminalCwd) {
const previewModel = new PreviewModel(previewId, null);
previewModel.isUpdatingFromTerminal = true;
try {
await previewModel.goHistory(terminalCwd);
} finally {
previewModel.isUpdatingFromTerminal = false;
}
}
}

1 change: 1 addition & 0 deletions frontend/types/gotypes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ declare global {
"frame:title"?: string;
"frame:icon"?: string;
"frame:text"?: string;
"preview:linked_terminal"?: string;
"cmd:*"?: boolean;
cmd?: string;
"cmd:interactive"?: boolean;
Expand Down
2 changes: 2 additions & 0 deletions pkg/waveobj/metaconsts.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const (
MetaKey_FrameIcon = "frame:icon"
MetaKey_FrameText = "frame:text"

MetaKey_PreviewLinkedTerminal = "preview:linked_terminal"

MetaKey_CmdClear = "cmd:*"
MetaKey_Cmd = "cmd"
MetaKey_CmdInteractive = "cmd:interactive"
Expand Down
4 changes: 4 additions & 0 deletions pkg/waveobj/wtypemeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ type MetaTSType struct {
FrameIcon string `json:"frame:icon,omitempty"`
FrameText string `json:"frame:text,omitempty"`

// Preview options
PreviewLinkedTerminal string `json:"preview:linked_terminal,omitempty"`

// Command options
CmdClear bool `json:"cmd:*,omitempty"`
Cmd string `json:"cmd,omitempty"`
CmdInteractive bool `json:"cmd:interactive,omitempty"`
Expand Down