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

Conversation

prawwtocol
Copy link

@prawwtocol prawwtocol commented Jan 25, 2025

Introduces new features for linking preview and terminal blocks:

  • Added metadata for tracking linked terminals
  • Implemented menu options to link/unlink terminals
  • Created sync mechanism to update terminal context when changing directories
  • Extended type definitions to support new metadata

Great project! I really wanted this feature, so I implemented it. I'm willing to refactor my code in any way necessary -- but only after my functional programming exam :)

Please see the attached video for an explanation on what the PR tries to accomplish.

CleanShot.2025-01-26.at.00.06.49.mp4

Introduces new features for linking preview and terminal blocks:
- Added metadata for tracking linked terminals
- Implemented menu options to link/unlink terminals
- Created sync mechanism to update terminal context when changing directories
- Extended type definitions to support new metadata
@CLAassistant
Copy link

CLAassistant commented Jan 25, 2025

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

/usr/local/bin/yarn: 3: dirname: not found
/usr/local/bin/yarn: 7: dirname: not found
node:internal/modules/cjs/loader:1251
throw err;
^

Error: Cannot find module '/yarn.js'
at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
at Module._load (node:internal/modules/cjs/loader:1074:27)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:166:5)
at node:internal/main/run_main_module:30:49 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Node.js v22.9.0

Walkthrough

The pull request introduces enhancements for synchronizing terminal and preview functionalities within the application. Key changes include the addition of two new functions, useTerminalPreviewSync and toggleTerminalPreviewLink, which facilitate the linking and unlinking of a terminal to a preview pane. A new boolean property, isUpdatingFromTerminal, is added to the PreviewModel class to manage terminal linking behavior during file navigation.

Furthermore, the MetaType interface is extended to include optional properties for linked terminal IDs and current working directories. A new constant, MetaKey_PreviewLinkedTerminal, is introduced in the waveobj package, alongside a new field in the MetaTSType struct to accommodate the linked terminal feature. These changes collectively enhance the interaction between terminal and preview functionalities, allowing for a more integrated user experience in managing files and directories.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
frontend/app/view/preview/sync.ts (2)

18-21: Add more descriptive documentation.

These lines contain a high-level description, but it might be helpful to provide additional details on prerequisites or usage scenarios for future maintainers unfamiliar with this mechanism. Consider elaborating on how the synchronization is triggered or suspended.


36-41: Handle errors from goHistory more explicitly.

Although the catch block delegates errors to console.error, consider surfacing them at the UI level or employing a global error-handling mechanism to improve reliability. This is especially important if directory changes can fail or be restricted.

pkg/waveobj/wtypemeta.go (1)

39-40: Ensure optional field usage is deliberate.

PreviewLinkedTerminal being a raw string instead of a pointer is fine if you plan on checking for empty strings. However, consider explicitly using a pointer (e.g., *string) to differentiate missing vs. empty states for more explicit null semantics in code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e6db9a and 3a762df.

📒 Files selected for processing (5)
  • frontend/app/view/preview/preview.tsx (6 hunks)
  • frontend/app/view/preview/sync.ts (1 hunks)
  • frontend/types/gotypes.d.ts (1 hunks)
  • pkg/waveobj/metaconsts.go (1 hunks)
  • pkg/waveobj/wtypemeta.go (1 hunks)
🔇 Additional comments (6)
frontend/app/view/preview/sync.ts (2)

23-50: Good subscription management in useTerminalPreviewSync.

This React hook correctly sets up and tears down the subscription to the terminal block when the linked terminal ID changes or when the component unmounts, preventing memory leaks. The approach appears robust and consistent with React best practices.


55-59: Verify that terminal objects always exist before unlinking.

When unlinking a terminal (lines 59-63), the code assumes the preview block is valid. Consider verifying the terminal block also exists and is in a valid state before clearing the linkage, to avoid edge-case issues or race conditions if the terminal block is missing.

pkg/waveobj/metaconsts.go (1)

40-40: Constant naming is consistent.

MetaKey_PreviewLinkedTerminal follows the naming pattern of existing MetaKey_* constants. This helps maintain readability and consistency across the codebase.

frontend/types/gotypes.d.ts (1)

498-498: LGTM! The new property follows the established conventions.

The "preview:linked_terminal" property is well-defined, following the existing naming pattern and type conventions in the codebase.

frontend/app/view/preview/preview.tsx (2)

47-48: LGTM! Clean imports and property initialization.

The new imports and property are well-organized and properly initialized.

Also applies to: 177-177


1074-1074: LGTM! Hook placement is correct.

The useTerminalPreviewSync hook is properly placed before any conditional returns in the component.

frontend/app/view/preview/sync.ts Outdated Show resolved Hide resolved
Comment on lines +712 to +734

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);
}
}),
});

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.

frontend/app/view/preview/preview.tsx Outdated Show resolved Hide resolved
prawwtocol and others added 2 commits January 26, 2025 00:36
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
frontend/app/view/preview/preview.tsx (1)

535-558: Extract terminal synchronization logic into a helper method.

Consider extracting the terminal synchronization logic into a separate method to improve readability and maintainability.

Apply this diff to refactor the code:

+    private async syncTerminalDirectory(terminalId: string, newPath: string) {
+        try {
+            const fileInfo = await RpcApi.FileInfoCommand(TabRpcClient, {
+                info: {
+                    path: await this.formatRemoteUri(newPath, globalStore.get),
+                },
+            });
+            if (fileInfo?.isdir) {
+                const terminalBlockRef = WOS.makeORef("block", terminalId);
+                await services.ObjectService.UpdateObjectMeta(terminalBlockRef, {
+                    "cmd:cwd": fileInfo.dir
+                });
+                
+                await RpcApi.ControllerInputCommand(TabRpcClient, {
+                    blockid: terminalId,
+                    inputdata64: btoa(`cd "${fileInfo.dir}"\n`),
+                });
+            }
+        } catch (error) {
+            console.error("Failed to sync terminal directory:", error);
+            // Consider showing a user-friendly error notification
+        }
+    }

     async goHistory(newPath: string) {
         // ... existing code ...
         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
-            }
+            await this.syncTerminalDirectory(linkedTerminalId, newPath);
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a762df and cbeae6a.

📒 Files selected for processing (2)
  • frontend/app/view/preview/preview.tsx (6 hunks)
  • frontend/app/view/preview/sync.ts (1 hunks)
🔇 Additional comments (6)
frontend/app/view/preview/sync.ts (3)

1-10: LGTM!

The license and imports are properly defined.


11-16: LGTM!

The MetaType interface is correctly extended with the necessary properties for terminal linking functionality.


18-50: 🛠️ Refactor suggestion

Add error handling for terminal synchronization.

While the synchronization logic is sound, consider adding error handling for the goHistory call to prevent unhandled promise rejections.

Apply this diff to improve error handling:

-                previewModel.goHistory(terminalCwd)
-                    .catch(console.error)
-                    .finally(() => {
-                        previewModel.isUpdatingFromTerminal = false;
-                    });
+                try {
+                    await previewModel.goHistory(terminalCwd);
+                } catch (err) {
+                    console.error("Failed to sync preview with terminal directory:", err);
+                    // Consider showing a user-friendly error notification
+                } finally {
+                    previewModel.isUpdatingFromTerminal = false;
+                }

Likely invalid or redundant comment.

frontend/app/view/preview/preview.tsx (3)

47-48: LGTM!

The required functions are properly imported from the sync module.


177-177: LGTM!

The isUpdatingFromTerminal property is correctly added and initialized to prevent circular updates during terminal synchronization.

Also applies to: 456-456


717-739: 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

Comment on lines +52 to +86
/**
* 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;
}
}
}
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;
}
}
}

@sawka
Copy link
Member

sawka commented Jan 27, 2025

Thanks for submitting! Just checked out the video and it looks cool! Will try to take a look at the implementation on Monday

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants