Skip to content

Add terminal link component #1538

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 2 commits into from
May 18, 2022
Merged
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
16 changes: 16 additions & 0 deletions site/src/components/TerminalLink/TerminalLink.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Story } from "@storybook/react"
import React from "react"
import { MockWorkspace } from "../../testHelpers/renderHelpers"
import { TerminalLink, TerminalLinkProps } from "./TerminalLink"

export default {
title: "components/TerminalLink",
component: TerminalLink,
}

const Template: Story<TerminalLinkProps> = (args) => <TerminalLink {...args} />

export const Example = Template.bind({})
Example.args = {
workspaceName: MockWorkspace.name,
}
28 changes: 28 additions & 0 deletions site/src/components/TerminalLink/TerminalLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Link from "@material-ui/core/Link"
import React from "react"
import * as TypesGen from "../../api/typesGenerated"

export const Language = {
linkText: "Open in terminal",
}

export interface TerminalLinkProps {
agentName?: TypesGen.WorkspaceAgent["name"]
userName?: TypesGen.User["username"]
workspaceName: TypesGen.Workspace["name"]
}

/**
* Generate a link to a terminal connected to the provided workspace agent. If
* no agent is provided connect to the first agent.
*
* If no user name is provided "me" is used however it makes the link not
* shareable.
*/
export const TerminalLink: React.FC<TerminalLinkProps> = ({ agentName, userName = "me", workspaceName }) => {
return (
<Link href={`/${userName}/${workspaceName}${agentName ? `.${agentName}` : ""}/terminal`} target="_blank">
{Language.linkText}
</Link>
)
}
20 changes: 18 additions & 2 deletions site/src/pages/TerminalPage/TerminalPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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/renderHelpers"
import { history, MockWorkspace, MockWorkspaceAgent, render } from "../../testHelpers/renderHelpers"
import { server } from "../../testHelpers/server"
import TerminalPage, { Language } from "./TerminalPage"

Expand Down Expand Up @@ -52,7 +52,7 @@ const expectTerminalText = (container: HTMLElement, text: string) => {

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

it("shows an error if fetching organizations fails", async () => {
Expand Down Expand Up @@ -146,4 +146,20 @@ describe("TerminalPage", () => {
expect(req.width).toBeGreaterThan(0)
server.close()
})

it("supports workspace.agent syntax", async () => {
// Given
const server = new WS("ws://localhost/api/v2/workspaceagents/" + MockWorkspaceAgent.id + "/pty")
const text = "something to render"

// When
history.push(`/some-user/${MockWorkspace.name}.${MockWorkspaceAgent.name}/terminal`)
const { container } = renderTerminal()

// Then
await server.connected
server.send(text)
await expectTerminalText(container, text)
server.close()
})
})
6 changes: 5 additions & 1 deletion site/src/pages/TerminalPage/TerminalPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,14 @@ const TerminalPage: React.FC<{
const search = new URLSearchParams(location.search)
return search.get("reconnect") ?? uuidv4()
})
// The workspace name is in the format:
// <workspace name>[.<agent name>]
const workspaceNameParts = workspace?.split(".")
const [terminalState, sendEvent] = useMachine(terminalMachine, {
context: {
agentName: workspaceNameParts?.[1],
reconnection: reconnectionToken,
workspaceName: workspace,
workspaceName: workspaceNameParts?.[0],
username: username,
},
actions: {
Expand Down
11 changes: 10 additions & 1 deletion site/src/testHelpers/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,16 @@ export const handlers = [

// workspaces
rest.get("/api/v2/organizations/:organizationId/workspaces/:userName/:workspaceName", (req, res, ctx) => {
return res(ctx.status(200), ctx.json(M.MockWorkspace))
if (req.params.workspaceName !== M.MockWorkspace.name) {
return res(
ctx.status(404),
ctx.json({
message: "workspace not found",
}),
)
} else {
return res(ctx.status(200), ctx.json(M.MockWorkspace))
}
}),
rest.get("/api/v2/workspaces/:workspaceId", async (req, res, ctx) => {
return res(ctx.status(200), ctx.json(M.MockWorkspace))
Expand Down
17 changes: 8 additions & 9 deletions site/src/xServices/terminal/terminalXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ export interface TerminalContext {
websocketError?: Error | unknown

// Assigned by connecting!
// The workspace agent is entirely optional. If the agent is omitted the
// first agent will be used.
agentName?: string
username?: string
workspaceName?: string
reconnection?: string
}

export type TerminalEvent =
| { type: "CONNECT"; reconnection?: string; workspaceName?: string; username?: string }
| { type: "CONNECT"; agentName?: string; reconnection?: string; workspaceName?: string; username?: string }
| { type: "WRITE"; request: Types.ReconnectingPTYRequest }
| { type: "READ"; data: ArrayBuffer }
| { type: "DISCONNECT" }
Expand Down Expand Up @@ -153,19 +156,14 @@ export const terminalMachine =
getOrganizations: API.getOrganizations,
getWorkspace: async (context) => {
if (!context.organizations || !context.workspaceName) {
throw new Error("organizations or workspace not set")
throw new Error("organizations or workspace name not set")
}
return API.getWorkspaceByOwnerAndName(context.organizations[0].id, context.username, context.workspaceName)
},
getWorkspaceAgent: async (context) => {
if (!context.workspace || !context.workspaceName) {
throw new Error("workspace or workspace name is not set")
}
// The workspace name is in the format:
// <workspace name>[.<agent name>]
// The workspace agent is entirely optional.
const workspaceNameParts = context.workspaceName.split(".")
const agentName = workspaceNameParts[1]

const resources = await API.getWorkspaceResources(context.workspace.latest_build.id)

Expand All @@ -174,10 +172,10 @@ export const terminalMachine =
if (!resource.agents || resource.agents.length < 1) {
return
}
if (!agentName) {
if (!context.agentName) {
return resource.agents[0]
}
return resource.agents.find((agent) => agent.name === agentName)
return resource.agents.find((agent) => agent.name === context.agentName)
})
.filter((a) => a)[0]
if (!agent) {
Expand Down Expand Up @@ -218,6 +216,7 @@ export const terminalMachine =
actions: {
assignConnection: assign((context, event) => ({
...context,
agentName: event.agentName ?? context.agentName,
reconnection: event.reconnection ?? context.reconnection,
workspaceName: event.workspaceName ?? context.workspaceName,
})),
Expand Down