• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 951400782

pending completion
951400782

Pull #3900

gitlab-ci

web-flow
chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 5.16.5 to 5.17.0.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v5.16.5...v5.17.0)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #3900: chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

4446 of 6414 branches covered (69.32%)

8342 of 10084 relevant lines covered (82.73%)

186.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

57.07
/src/js/components/devices/dialogs/troubleshootdialog.js
1
// Copyright 2021 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useRef, useState } from 'react';
15
import Dropzone from 'react-dropzone';
16
import { useDispatch, useSelector } from 'react-redux';
17
import { Link } from 'react-router-dom';
18

19
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Tab, Tabs } from '@mui/material';
20
import { makeStyles } from 'tss-react/mui';
21

22
import { mdiConsole as ConsoleIcon } from '@mdi/js';
23
import moment from 'moment';
24
import momentDurationFormatSetup from 'moment-duration-format';
25

26
import { setSnackbar } from '../../../actions/appActions';
27
import { deviceFileUpload, getDeviceFileDownloadLink } from '../../../actions/deviceActions';
28
import { BEGINNING_OF_TIME, TIMEOUTS } from '../../../constants/appConstants';
29
import { createDownload } from '../../../helpers';
30
import { getFeatures, getIsEnterprise, getIsPreview, getTenantCapabilities, getUserCapabilities } from '../../../selectors';
31
import { useSession } from '../../../utils/sockethook';
32
import { TwoColumns } from '../../common/configurationobject';
33
import MaterialDesignIcon from '../../common/materialdesignicon';
34
import { MaybeTime } from '../../common/time';
35
import FileTransfer from '../troubleshoot/filetransfer';
36
import Terminal from '../troubleshoot/terminal';
37
import ListOptions from '../widgets/listoptions';
38
import DeviceIdentityDisplay from './../../common/deviceidentity';
39
import { getCode } from './make-gateway-dialog';
40

41
momentDurationFormatSetup(moment);
12✔
42

43
const useStyles = makeStyles()(theme => ({
12✔
44
  content: { padding: 0, margin: '0 24px', height: '75vh' },
45
  title: { marginRight: theme.spacing(0.5) },
46
  connectionButton: { background: theme.palette.text.primary },
47
  connectedIcon: { color: theme.palette.success.main, marginLeft: theme.spacing() },
48
  disconnectedIcon: { color: theme.palette.error.main, marginLeft: theme.spacing() },
49
  sessionInfo: { maxWidth: 'max-content' },
50
  terminalContent: {
51
    display: 'grid',
52
    gridTemplateRows: 'max-content 0',
53
    flexGrow: 1,
54
    overflow: 'hidden',
55
    '&.device-connected': {
56
      gridTemplateRows: 'max-content minmax(min-content, 1fr)'
57
    }
58
  },
59
  terminalStatePlaceholder: {
60
    width: 280
61
  }
62
}));
63

64
const ConnectionIndicator = ({ isConnected }) => {
12✔
65
  const { classes } = useStyles();
1✔
66
  return (
1✔
67
    <div className="flexbox center-aligned">
68
      Remote terminal {<MaterialDesignIcon className={isConnected ? classes.connectedIcon : classes.disconnectedIcon} path={ConsoleIcon} />}
1!
69
    </div>
70
  );
71
};
72

73
const tabs = {
12✔
74
  terminal: {
75
    link: 'session logs',
76
    title: ConnectionIndicator,
77
    value: 'terminal',
78
    canShow: ({ canTroubleshoot, canWriteDevices }) => canTroubleshoot && canWriteDevices
1✔
79
  },
80
  transfer: { link: 'file transfer logs', title: () => 'File transfer', value: 'transfer', canShow: ({ canTroubleshoot }) => canTroubleshoot }
1✔
81
};
82

83
export const TroubleshootDialog = ({ device, onCancel, open, setSocketClosed, type = tabs.terminal.value }) => {
12✔
84
  const [currentTab, setCurrentTab] = useState(type);
2✔
85
  const [availableTabs, setAvailableTabs] = useState(Object.values(tabs));
2✔
86
  const [downloadPath, setDownloadPath] = useState('');
2✔
87
  const [elapsed, setElapsed] = useState(moment());
2✔
88
  const [file, setFile] = useState();
2✔
89
  const [socketInitialized, setSocketInitialized] = useState(false);
2✔
90
  const [startTime, setStartTime] = useState();
2✔
91
  const [uploadPath, setUploadPath] = useState('');
2✔
92
  const [terminalInput, setTerminalInput] = useState('');
2✔
93
  const [snackbarAlreadySet, setSnackbarAlreadySet] = useState(false);
2✔
94
  const closeTimer = useRef();
2✔
95
  const snackTimer = useRef();
2✔
96
  const timer = useRef();
2✔
97
  const termRef = useRef({ terminal: React.createRef(), terminalRef: React.createRef() });
2✔
98
  const { classes } = useStyles();
2✔
99
  const { isHosted } = useSelector(getFeatures);
2✔
100
  const isEnterprise = useSelector(getIsEnterprise);
2✔
101
  const canPreview = useSelector(getIsPreview);
2✔
102
  const userCapabilities = useSelector(getUserCapabilities);
2✔
103
  const { canAuditlog, canTroubleshoot, canWriteDevices } = userCapabilities;
2✔
104
  const { hasAuditlogs } = useSelector(getTenantCapabilities);
2✔
105
  const dispatch = useDispatch();
2✔
106
  const dispatchedSetSnackbar = (...args) => dispatch(setSnackbar(...args));
2✔
107

108
  useEffect(() => {
2✔
109
    if (open) {
1!
110
      setCurrentTab(type);
1✔
111
      return;
1✔
112
    }
113
    setDownloadPath('');
×
114
    setUploadPath('');
×
115
    setFile();
×
116
    return () => {
×
117
      clearTimeout(closeTimer.current);
×
118
      clearTimeout(snackTimer.current);
×
119
    };
120
  }, [open]);
121

122
  useEffect(() => {
2✔
123
    const allowedTabs = Object.values(tabs).reduce((accu, tab) => {
1✔
124
      if (tab.canShow(userCapabilities)) {
2!
125
        accu.push(tab);
2✔
126
      }
127
      return accu;
2✔
128
    }, []);
129
    setAvailableTabs(allowedTabs);
1✔
130
  }, [canTroubleshoot, canWriteDevices]);
131

132
  useEffect(() => {
2✔
133
    if (socketInitialized === undefined) {
2✔
134
      return;
1✔
135
    }
136
    clearInterval(timer.current);
1✔
137
    if (socketInitialized) {
1!
138
      setStartTime(new Date());
×
139
      timer.current = setInterval(() => setElapsed(moment()), TIMEOUTS.halfASecond);
×
140
    } else {
141
      close();
1✔
142
    }
143
    return () => {
1✔
144
      clearInterval(timer.current);
1✔
145
    };
146
  }, [socketInitialized]);
147

148
  useEffect(() => {
2✔
149
    if (!(open || socketInitialized) || socketInitialized) {
1!
150
      return;
×
151
    }
152
    canTroubleshoot ? connect(device.id) : undefined;
1!
153
    return () => {
1✔
154
      close();
1✔
155
      setTimeout(() => setSocketClosed(true), TIMEOUTS.fiveSeconds);
1✔
156
    };
157
  }, [device.id, open]);
158

159
  const onConnectionToggle = () => {
2✔
160
    if (socketInitialized) {
×
161
      close();
×
162
    } else {
163
      setSocketInitialized(false);
×
164
      connect(device.id);
×
165
    }
166
  };
167

168
  const onDrop = acceptedFiles => {
2✔
169
    if (acceptedFiles.length === 1) {
×
170
      setFile(acceptedFiles[0]);
×
171
      setUploadPath(`/tmp/${acceptedFiles[0].name}`);
×
172
      setCurrentTab(tabs.transfer.value);
×
173
    }
174
  };
175

176
  const onDownloadClick = path => {
2✔
177
    setDownloadPath(path);
×
178
    dispatch(getDeviceFileDownloadLink(device.id, path)).then(address => {
×
179
      const filename = path.substring(path.lastIndexOf('/') + 1) || 'file';
×
180
      createDownload(address, filename);
×
181
    });
182
  };
183

184
  const onSocketOpen = () => {
2✔
185
    setSocketInitialized(true);
×
186
    dispatch(setSnackbar('Connection with the device established.', TIMEOUTS.fiveSeconds));
×
187
  };
188

189
  const onNotify = content => {
2✔
190
    setSnackbarAlreadySet(true);
×
191
    dispatch(setSnackbar(content, TIMEOUTS.fiveSeconds));
×
192
    snackTimer.current = setTimeout(() => setSnackbarAlreadySet(false), TIMEOUTS.fiveSeconds + TIMEOUTS.debounceShort);
×
193
  };
194

195
  const onHealthCheckFailed = () => {
2✔
196
    if (snackbarAlreadySet) {
×
197
      return;
×
198
    }
199
    onNotify('Health check failed: connection with the device lost.');
×
200
  };
201

202
  const onSocketClose = event => {
2✔
203
    if (snackbarAlreadySet) {
×
204
      return;
×
205
    }
206
    if (event.wasClean) {
×
207
      onNotify(`Connection with the device closed.`);
×
208
    } else if (event.code == 1006) {
×
209
      // 1006: abnormal closure
210
      onNotify('Connection to the remote terminal is forbidden.');
×
211
    } else {
212
      onNotify('Connection with the device died.');
×
213
    }
214
    closeTimer.current = setTimeout(() => setSocketClosed(true), TIMEOUTS.fiveSeconds);
×
215
  };
216

217
  const onMessageReceived = useCallback(
2✔
218
    message => {
219
      if (!termRef.current.terminal) {
×
220
        return;
×
221
      }
222
      termRef.current.terminal.write(new Uint8Array(message));
×
223
    },
224
    [termRef.current]
225
  );
226

227
  const [connect, sendMessage, close, sessionState, sessionId] = useSession({
2✔
228
    onClose: onSocketClose,
229
    onHealthCheckFailed,
230
    onMessageReceived,
231
    onNotify,
232
    onOpen: onSocketOpen
233
  });
234

235
  useEffect(() => {
2✔
236
    setSocketInitialized(sessionState === WebSocket.OPEN && sessionId);
1✔
237
  }, [sessionId, sessionState]);
238

239
  const onMakeGatewayClick = () => {
2✔
240
    const code = getCode(canPreview);
×
241
    setTerminalInput(code);
×
242
  };
243

244
  const commandHandlers = isHosted && isEnterprise ? [{ key: 'thing', onClick: onMakeGatewayClick, title: 'Promote to Mender gateway' }] : [];
2!
245

246
  const duration = moment.duration(elapsed.diff(moment(startTime)));
2✔
247
  const visibilityToggle = !socketInitialized ? { maxHeight: 0, overflow: 'hidden' } : {};
2!
248
  return (
2✔
249
    <Dialog open={open} fullWidth={true} maxWidth="lg">
250
      <DialogTitle className="flexbox">
251
        <div className={classes.title}>Troubleshoot -</div>
252
        <DeviceIdentityDisplay device={device} isEditable={false} />
253
      </DialogTitle>
254
      <DialogContent className={`dialog-content flexbox column ${classes.content}`}>
255
        <Tabs value={currentTab} onChange={(e, tab) => setCurrentTab(tab)} textColor="primary" TabIndicatorProps={{ className: 'hidden' }}>
×
256
          {availableTabs.map(({ title: Title, value }) => (
257
            <Tab key={value} label={<Title isConnected={socketInitialized} />} value={value} />
4✔
258
          ))}
259
        </Tabs>
260
        {currentTab === tabs.transfer.value && (
2!
261
          <FileTransfer
262
            deviceId={device.id}
263
            downloadPath={downloadPath}
264
            file={file}
265
            onDownload={onDownloadClick}
266
            onUpload={(...args) => dispatch(deviceFileUpload(...args))}
×
267
            setDownloadPath={setDownloadPath}
268
            setFile={setFile}
269
            setSnackbar={dispatchedSetSnackbar}
270
            setUploadPath={setUploadPath}
271
            uploadPath={uploadPath}
272
            userCapabilities={userCapabilities}
273
          />
274
        )}
275
        <div className={`${classes.terminalContent} ${socketInitialized ? 'device-connected' : ''} ${currentTab === tabs.terminal.value ? '' : 'hidden'}`}>
4!
276
          <TwoColumns
277
            className={`margin-top-small margin-bottom-small ${classes.sessionInfo}`}
278
            items={{
279
              'Session status': socketInitialized ? 'connected' : 'disconnected',
2!
280
              'Connection start': <MaybeTime value={startTime} />,
281
              'Duration': `${duration.format('hh:mm:ss', { trim: false })}`
282
            }}
283
          />
284
          <Dropzone activeClassName="active" rejectClassName="active" multiple={false} onDrop={onDrop} noClick>
285
            {({ getRootProps }) => (
286
              <div {...getRootProps()} style={{ position: 'relative', ...visibilityToggle }}>
1✔
287
                <Terminal
288
                  onDownloadClick={onDownloadClick}
289
                  sendMessage={sendMessage}
290
                  sessionId={sessionId}
291
                  setSnackbar={dispatchedSetSnackbar}
292
                  socketInitialized={socketInitialized}
293
                  style={{ position: 'absolute', width: '100%', height: '100%', ...visibilityToggle }}
294
                  textInput={terminalInput}
295
                  xtermRef={termRef}
296
                />
297
              </div>
298
            )}
299
          </Dropzone>
300
          {!socketInitialized && (
4✔
301
            <div className={`flexbox centered ${classes.connectionButton}`}>
302
              <Button variant="contained" color="secondary" onClick={onConnectionToggle}>
303
                Connect Terminal
304
              </Button>
305
            </div>
306
          )}
307
        </div>
308
      </DialogContent>
309
      <DialogActions className="flexbox space-between">
310
        <div>
311
          {currentTab === tabs.terminal.value ? (
2!
312
            <Button onClick={onConnectionToggle}>{socketInitialized ? 'Disconnect' : 'Connect'} Terminal</Button>
2!
313
          ) : (
314
            <div className={classes.terminalStatePlaceholder} />
315
          )}
316
          {canAuditlog && hasAuditlogs && (
4!
317
            <Button component={Link} to={`/auditlog?objectType=device&objectId=${device.id}&startDate=${BEGINNING_OF_TIME}`}>
318
              View {tabs[currentTab].link} for this device
319
            </Button>
320
          )}
321
        </div>
322
        <div>
323
          {currentTab === tabs.terminal.value && socketInitialized && !!commandHandlers.length && (
4!
324
            <ListOptions options={commandHandlers} title="Quick commands" />
325
          )}
326
          <Button onClick={onCancel}>Close</Button>
327
        </div>
328
      </DialogActions>
329
    </Dialog>
330
  );
331
};
332

333
export default TroubleshootDialog;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc