Skip to content

feat: Add web terminal with reconnecting TTYs #1186

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

Merged
merged 8 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add terminal page tests
  • Loading branch information
kylecarbs committed Apr 29, 2022
commit 229c7e480d12bc80c971b055bf6daef7390a9959
2 changes: 1 addition & 1 deletion agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ func (a *agent) handleReconnectingPTY(ctx context.Context, rawID string, conn ne
go func() {
// When the context has been completed either:
// 1. The timeout completed.
// 2. The parent context was cancelled.
// 2. The parent context was canceled.
<-ctx.Done()
_ = process.Kill()
}()
Expand Down
3 changes: 3 additions & 0 deletions site/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ module.exports = {
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
testPathIgnorePatterns: ["/node_modules/", "/__tests__/fakes", "/e2e/"],
moduleDirectories: ["node_modules", "<rootDir>"],
moduleNameMapper: {
"\\.css$": "<rootDir>/src/testHelpers/styleMock.ts",
},
},
{
displayName: "lint",
Expand Down
3 changes: 3 additions & 0 deletions site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"react-router-dom": "6.3.0",
"swr": "1.2.2",
"xstate": "4.31.0",
"xterm": "^4.18.0",
"xterm-addon-fit": "^0.5.0",
"xterm-addon-web-links": "^0.5.1",
"xterm-addon-webgl": "^0.11.4",
Expand Down Expand Up @@ -84,8 +85,10 @@
"eslint-plugin-react-hooks": "4.4.0",
"html-webpack-plugin": "5.5.0",
"jest": "27.5.1",
"jest-canvas-mock": "^2.4.0",
"jest-junit": "13.1.0",
"jest-runner-eslint": "1.0.0",
"jest-websocket-mock": "^2.3.0",
"mini-css-extract-plugin": "2.6.0",
"msw": "0.39.2",
"prettier": "2.6.2",
Expand Down
8 changes: 6 additions & 2 deletions site/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,13 @@ export const getOrganizations = async (): Promise<Types.Organization[]> => {
return response.data
}

export const getWorkspace = async (organizationID: string, workspaceName: string): Promise<Types.Workspace> => {
export const getWorkspace = async (
organizationID: string,
username = "me",
workspaceName: string,
): Promise<Types.Workspace> => {
const response = await axios.get<Types.Workspace>(
`/api/v2/organizations/${organizationID}/workspaces/me/${workspaceName}`,
`/api/v2/organizations/${organizationID}/workspaces/${username}/${workspaceName}`,
)
return response.data
}
Expand Down
156 changes: 156 additions & 0 deletions site/src/pages/TerminalPage/TerminalPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { waitFor } from "@testing-library/react"
import crypto from "crypto"
import "jest-canvas-mock"
import WS from "jest-websocket-mock"
import { rest } from "msw"
import React from "react"
import { Route, Routes } from "react-router-dom"
import { TextDecoder, TextEncoder } from "util"
import { ReconnectingPTYRequest } from "../../api/types"
import { history, MockWorkspaceAgent, render } from "../../testHelpers"
import { server } from "../../testHelpers/server"
import { Language, TerminalPage } from "./TerminalPage"

Object.defineProperty(window, "matchMedia", {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
})

Object.defineProperty(window, "crypto", {
value: {
randomUUID: () => crypto.randomUUID(),
},
})

Object.defineProperty(window, "TextEncoder", {
value: TextEncoder,
})

const renderTerminal = () => {
return render(
<Routes>
<Route path="/:username/:workspace/terminal" element={<TerminalPage renderer="dom" />} />
</Routes>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Ooh, curious why you put Routes in here, it might help me with some pain points I've had

Copy link
Member Author

Choose a reason for hiding this comment

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

It said it was required for me to use <Route /> :(

)
}

const expectTerminalText = (container: HTMLElement, text: string) => {
return waitFor(() => {
const elements = container.getElementsByClassName("xterm-rows")
if (elements.length < 1) {
throw new Error("no xterm-rows")
}
const row = elements[0] as HTMLDivElement
if (!row.textContent) {
throw new Error("no text content")
}
expect(row.textContent).toContain(text)
})
}

describe("TerminalPage", () => {
beforeEach(() => {
history.push("/some-user/my-workspace/terminal")
})

it("shows an error if fetching organizations fails", async () => {
// Given
server.use(
rest.get("/api/v2/users/me/organizations", async (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ message: "nope" }))
}),
)

// When
const { container } = renderTerminal()

// Then
await expectTerminalText(container, Language.organizationsErrorMessagePrefix)
})

it("shows an error if fetching workspace fails", async () => {
// Given
server.use(
rest.get("/api/v2/organizations/:organizationId/workspaces/:userName/:workspaceName", (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ id: "workspace-id" }))
}),
)

// When
const { container } = renderTerminal()

// Then
await expectTerminalText(container, Language.workspaceErrorMessagePrefix)
})

it("shows an error if fetching workspace agent fails", async () => {
// Given
server.use(
rest.get("/api/v2/workspacebuilds/:workspaceId/resources", (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ message: "nope" }))
}),
)

// When
const { container } = renderTerminal()

// Then
await expectTerminalText(container, Language.workspaceAgentErrorMessagePrefix)
})

it("shows an error if the websocket fails", async () => {
// Given
server.use(
rest.get("/api/v2/workspaceagents/:agentId/pty", (req, res, ctx) => {
return res(ctx.status(500), ctx.json({}))
}),
)

// When
const { container } = renderTerminal()

// Then
await expectTerminalText(container, Language.websocketErrorMessagePrefix)
})

it("renders data from the backend", async () => {
// Given
const server = new WS("ws://localhost/api/v2/workspaceagents/" + MockWorkspaceAgent.id + "/pty")
const text = "something to render"

// When
const { container } = renderTerminal()

// Then
await server.connected
server.send(text)
await expectTerminalText(container, text)
server.close()
})

it("resizes on connect", async () => {
// Given
const server = new WS("ws://localhost/api/v2/workspaceagents/" + MockWorkspaceAgent.id + "/pty")

// When
renderTerminal()

// Then
await server.connected
const msg = await server.nextMessage
const req: ReconnectingPTYRequest = JSON.parse(new TextDecoder().decode(msg as Uint8Array))

expect(req.height).toBeGreaterThan(0)
expect(req.width).toBeGreaterThan(0)
server.close()
})
})
Loading