Skip to content
Closed
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
3 changes: 3 additions & 0 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ import { authService, handleAuthDeepLink, isAuthDeepLink } from "./lib/auth";
import { setupAutoUpdater } from "./lib/auto-updater";
import { localDb } from "./lib/local-db";
import { terminalManager } from "./lib/terminal";
import { registerDefaultFilters } from "./lib/terminal-output-filters";
import { MainWindow } from "./windows/main";

registerDefaultFilters();

// Initialize local SQLite database (runs migrations + legacy data migration on import)
console.log("[main] Local database ready:", !!localDb);

Expand Down
125 changes: 125 additions & 0 deletions apps/desktop/src/main/lib/terminal-output-filter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { beforeEach, describe, expect, it } from "bun:test";
import {
type TerminalOutputFilter,
TerminalOutputFilterChain,
} from "./terminal-output-filter";

describe("TerminalOutputFilterChain", () => {
let chain: TerminalOutputFilterChain;

beforeEach(() => {
chain = new TerminalOutputFilterChain();
});

describe("register", () => {
it("should register a filter", () => {
const filter: TerminalOutputFilter = {
id: "test-filter",
description: "Test filter",
filter: (data) => data.replace("foo", "bar"),
};

chain.register(filter);

expect(chain.getRegisteredFilters()).toEqual(["test-filter"]);
});

it("should not register duplicate filters", () => {
const filter: TerminalOutputFilter = {
id: "test-filter",
description: "Test filter",
filter: (data) => data,
};

chain.register(filter);
chain.register(filter);

expect(chain.getRegisteredFilters()).toEqual(["test-filter"]);
});
});

describe("unregister", () => {
it("should unregister a filter", () => {
const filter: TerminalOutputFilter = {
id: "test-filter",
description: "Test filter",
filter: (data) => data,
};

chain.register(filter);
const result = chain.unregister("test-filter");

expect(result).toBe(true);
expect(chain.getRegisteredFilters()).toEqual([]);
});

it("should return false for non-existent filter", () => {
const result = chain.unregister("non-existent");
expect(result).toBe(false);
});
});

describe("apply", () => {
it("should apply filters in order", () => {
chain.register({
id: "filter-1",
description: "Add A",
filter: (data) => `${data}A`,
});
chain.register({
id: "filter-2",
description: "Add B",
filter: (data) => `${data}B`,
});

const result = chain.apply("X");
expect(result).toBe("XAB");
});

it("should stop early if data is empty", () => {
let secondFilterCalled = false;

chain.register({
id: "filter-1",
description: "Clear all",
filter: () => "",
});
chain.register({
id: "filter-2",
description: "Should not be called",
filter: (data) => {
secondFilterCalled = true;
return data;
},
});

const result = chain.apply("test");
expect(result).toBe("");
expect(secondFilterCalled).toBe(false);
});

it("should return original data with no filters", () => {
const result = chain.apply("test data");
expect(result).toBe("test data");
});
});

describe("clear", () => {
it("should remove all filters", () => {
chain.register({
id: "filter-1",
description: "Filter 1",
filter: (data) => data,
});
chain.register({
id: "filter-2",
description: "Filter 2",
filter: (data) => data,
});

chain.clear();

expect(chain.getRegisteredFilters()).toEqual([]);
});
});
});
50 changes: 50 additions & 0 deletions apps/desktop/src/main/lib/terminal-output-filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Terminal output filter - transforms data before display (not storage).
* Implement this interface to add custom filters.
*/
export interface TerminalOutputFilter {
readonly id: string;
readonly description: string;
filter(data: string): string;
}

export class TerminalOutputFilterChain {
private filters: TerminalOutputFilter[] = [];

register(filter: TerminalOutputFilter): void {
if (this.filters.some((f) => f.id === filter.id)) {
return;
}
this.filters.push(filter);
}

unregister(filterId: string): boolean {
const index = this.filters.findIndex((f) => f.id === filterId);
if (index === -1) {
return false;
}
this.filters.splice(index, 1);
return true;
}

apply(data: string): string {
let result = data;
for (const filter of this.filters) {
result = filter.filter(result);
if (result.length === 0) {
break;
}
Comment on lines +34 to +36

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Early break on empty string may prevent valid filter compositions.

The optimization that breaks when result.length === 0 assumes no filter needs to process or restore content from an empty string. This could prevent filter compositions where:

  • Filter A removes all content temporarily
  • Filter B needs to add content back or process the empty state

Consider whether this early exit aligns with your filtering requirements, or if filters should always run regardless of intermediate results.

🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal-output-filter.ts around lines 34 to 36,
the loop currently breaks when result.length === 0 which prevents later filters
from running and blocks compositions where a later filter might reintroduce or
process content; remove the early break so the loop continues applying remaining
filters even on an empty string (or, if you need performance control, replace
the unconditional break with a per-filter skip flag or check so only filters
that opt out are skipped while others still run).

}
return result;
}
Comment on lines +30 to +39

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add error handling to prevent filter chain failures.

If any filter throws an exception, the entire chain fails silently with no indication of which filter caused the problem. According to the coding guidelines, errors should never be swallowed silently.

🔎 Proposed fix with error handling
 apply(data: string): string {
   let result = data;
   for (const filter of this.filters) {
-    result = filter.filter(result);
+    try {
+      result = filter.filter(result);
+    } catch (error) {
+      console.error(`[terminal-output-filter/apply] Filter "${filter.id}" threw error:`, error);
+      // Continue with other filters or rethrow depending on desired behavior
+      // For now, continue to make the chain resilient
+    }
     if (result.length === 0) {
       break;
     }
   }
   return result;
 }
📝 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
apply(data: string): string {
let result = data;
for (const filter of this.filters) {
result = filter.filter(result);
if (result.length === 0) {
break;
}
}
return result;
}
apply(data: string): string {
let result = data;
for (const filter of this.filters) {
try {
result = filter.filter(result);
} catch (error) {
console.error(`[terminal-output-filter/apply] Filter "${filter.id}" threw error:`, error);
// Continue with other filters or rethrow depending on desired behavior
// For now, continue to make the chain resilient
}
if (result.length === 0) {
break;
}
}
return result;
}
🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal-output-filter.ts around lines 30 to 39,
wrap each call to filter.filter(result) in a try/catch so a thrown exception
from one filter is not swallowed silently; in the catch log/report the error
with identifying info (filter index and filter.constructor.name or a provided
name) and the error stack, then skip the failing filter and continue the chain
using the previous result (do not let one filter break the whole pipeline).


getRegisteredFilters(): string[] {
return this.filters.map((f) => f.id);
}

clear(): void {
this.filters = [];
}
}

export const terminalOutputFilterChain = new TerminalOutputFilterChain();
8 changes: 8 additions & 0 deletions apps/desktop/src/main/lib/terminal-output-filters/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { terminalOutputFilterChain } from "../terminal-output-filter";
import { oscResponseFilter } from "./osc-response-filter";

export function registerDefaultFilters(): void {
terminalOutputFilterChain.register(oscResponseFilter);
}

export { oscResponseFilter };
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect, it } from "bun:test";
import { oscResponseFilter } from "./osc-response-filter";

const ESC = "\x1b";
const BEL = "\x07";

describe("oscResponseFilter", () => {
describe("OSC color responses", () => {
it("should filter OSC 11 background color response with BEL terminator", () => {
const response = `${ESC}]11;rgb:1a1a/1a1a/1a1a${BEL}`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter OSC 11 background color response with ST terminator", () => {
const response = `${ESC}]11;rgb:1a1a/1a1a/1a1a${ESC}\\`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter OSC 10 foreground color response", () => {
const response = `${ESC}]10;rgb:ffff/ffff/ffff${BEL}`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter OSC 12 cursor color response", () => {
const response = `${ESC}]12;rgb:0000/ffff/0000${BEL}`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter partial OSC response without ESC prefix", () => {
const response = "11;rgb:1a1a/1a1a/1a1a";
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter partial OSC response with trailing 1R", () => {
const response = "11;rgb:1a1a/1a1a/1a1a1R";
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should preserve normal text around OSC response", () => {
const data = `before${ESC}]11;rgb:1a1a/1a1a/1a1a${BEL}after`;
expect(oscResponseFilter.filter(data)).toBe("beforeafter");
});
});

describe("Device Attributes responses", () => {
it("should filter DA1 response", () => {
const response = `${ESC}[?1;2c`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter DA2 response with more params", () => {
const response = `${ESC}[?65;1;9c`;
expect(oscResponseFilter.filter(response)).toBe("");
});
});

describe("Cursor Position Report", () => {
it("should filter CPR response", () => {
const response = `${ESC}[24;80R`;
expect(oscResponseFilter.filter(response)).toBe("");
});

it("should filter CPR with different positions", () => {
const response = `${ESC}[1;1R`;
expect(oscResponseFilter.filter(response)).toBe("");
});
});

describe("mixed content", () => {
it("should filter multiple response types", () => {
const data = `text${ESC}]11;rgb:1a1a/1a1a/1a1a${BEL}more${ESC}[?1;2c${ESC}[24;80Rend`;
expect(oscResponseFilter.filter(data)).toBe("textmoreend");
});

it("should preserve ANSI color codes", () => {
const data = `${ESC}[32mgreen text${ESC}[0m`;
expect(oscResponseFilter.filter(data)).toBe(data);
});

it("should preserve normal escape sequences", () => {
const data = `${ESC}[H${ESC}[2J`;
expect(oscResponseFilter.filter(data)).toBe(data);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { TerminalOutputFilter } from "../terminal-output-filter";

const ESC = "\\x1b";
const BEL = "\\x07";

// OSC 10/11/12 color responses: \e]1X;rgb:RRRR/GGGG/BBBB\a or \e]1X;rgb:RRRR/GGGG/BBBB\e\\
const OSC_COLOR_RESPONSE = new RegExp(
`${ESC}\\]1[0-2];rgb:[0-9a-fA-F]{4}/[0-9a-fA-F]{4}/[0-9a-fA-F]{4}(?:${BEL}|${ESC}\\\\)`,
"g",
);

// Device Attributes response: \e[?...c
const DA_RESPONSE = new RegExp(`${ESC}\\[\\?[0-9;]*c`, "g");

// Cursor Position Report: \e[row;colR
const CPR_RESPONSE = new RegExp(`${ESC}\\[[0-9]+;[0-9]+R`, "g");

// Partial OSC responses without ESC prefix: 1X;rgb:XXXX/XXXX/XXXX...
const PARTIAL_OSC_COLOR =
/1[0-2];rgb:[0-9a-fA-F]{4}\/[0-9a-fA-F]{4}\/[0-9a-fA-F]{4}(?:1R)?/g;

export const oscResponseFilter: TerminalOutputFilter = {
id: "osc-response",
description: "Filters terminal query responses (OSC colors, DA, CPR)",

filter(data: string): string {
return data
.replace(OSC_COLOR_RESPONSE, "")
.replace(DA_RESPONSE, "")
.replace(CPR_RESPONSE, "")
.replace(PARTIAL_OSC_COLOR, "");
},
};
5 changes: 3 additions & 2 deletions apps/desktop/src/main/lib/terminal/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
extractContentAfterClear,
} from "../terminal-escape-filter";
import { HistoryReader, HistoryWriter } from "../terminal-history";
import { terminalOutputFilterChain } from "../terminal-output-filter";
import { buildTerminalEnv, FALLBACK_SHELL, getDefaultShell } from "./env";
import { portManager } from "./port-manager";
import type { InternalCreateSessionParams, TerminalSession } from "./types";
Expand Down Expand Up @@ -166,10 +167,10 @@ export function setupDataHandler(
session.scrollback += dataToStore;
session.historyWriter?.write(dataToStore);

// Scan for port patterns in terminal output
portManager.scanOutput(dataToStore, session.paneId, session.workspaceId);

session.dataBatcher.write(data);
const dataToDisplay = terminalOutputFilterChain.apply(data);
session.dataBatcher.write(dataToDisplay);

if (initialCommandString && !commandsSent) {
commandsSent = true;
Expand Down
Loading